Change variable scope

Description

Using the var operator to define a variable makes it local to the scope where it was defined.

Example

Defining a variable inside of a function with var means that the variable is local to that function and will be destroyed if the function exits, as shown here:


function test(){
   var myVariable = "hi";  //local variable
}
test();
console.log(myVariable); //error!

Here, the myVariable variable is defined within a function called test() using var.

Global

To define a variable globally, simply omitting the var operator as follows:


function test(){
   myVariable = "hi";  //global variable
}
test();
console.log(myVariable); //"hi"

By removing the var operator from the example, the myVariable variable becomes global.

Defining global variables is not recommended. Global variables defined locally are hard to maintain and cause confusion.

Strict mode throws a ReferenceError when an undeclared variable is assigned a value.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions