JavaScript Variable Scope

JavaScript Variable Scope

The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.

  • Global Variables− A global variable has global scope which means it can be defined anywhere in your JavaScript code.
  • Local Variables− A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.

<html>

<body onload = checkscope();>

<script type = “text/javascript”>

<!–

var myVar = “global”; // Declare a global variable

function checkscope( ) {

var myVar = “local”; // Declare a local variable

document.write(myVar);

}

//–>

</script>

</body>

</html>

This produces the following result −

local

JavaScript Variable Names

While naming your variables in JavaScript, keep the following rules in mind.

  • You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example,break or boolean variable names are not valid.
  • JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example,123testis an invalid variable name but _123test is a valid one.
  • JavaScript variable names are case-sensitive. For example,Name andname are two different variables.

JavaScript Reserved Words

A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.

abstract

boolean

break

byte

case

catch

char

class

const

continue

debugger

default

delete

do

double

else

enum

export

extends

false

final

finally

float

for

function

goto

if

implements

import

in

instanceof

int

interface

long

native

new

null

package

private

protected

public

return

short

static

super

switch

synchronized

this

throw

throws

transient

true

try

typeof

var

void

volatile

while

with

Leave a Reply