JavaScript Scope


The scope is a collection of accessible variables.


JavaScript Scope

In JavaScript, objects and functions are also variables.

In JavaScript, the scope is a collection of accessible variables, objects, and functions.

JavaScript function scope: The scope is modified within the function.


JavaScript Local Scope

Variables are declared in functions, and variables are of local scope.

Local variables: can only be accessed inside the function.

Example

// The carName variable cannot be called here
function myFunction() {
     var carName = "Dodge";
     // The carName variable can be called in the function
}

 Try It! 

Because local variables only work within functions, different functions can use variables with the same name.

Local variables are created when the function starts to execute, and the local variables are automatically destroyed after the function is executed.


JavaScript Global Variables

Variables defined outside the function are global variables.

Global variables have a global scope : pages all scripts and functions can be used. 

Example

var carName = "Dodge";
 
// The carName variable can be called here
function myFunction() {
     // The carName variable can be called in the function
}

 Try It! 

If the variable is not declared in the function (the var keyword is not used), the variable is a global variable.

In the following example, carName is in the function, but it is a global variable.

Example

// The carName variable can be called here
 
function myFunction() {
     carName = "Dodge";
     // The carName variable can be called here
}

 Try It! 


JavaScript Variable Life Cycle

The JavaScript variable life cycle is initialized when it is declared.

Local variables are destroyed after the function is executed.

Global variables are destroyed after the page is closed.


Function Parameters

Function parameters only work within the function and are local variables.


Global Variables in HTML

In HTML, global variables are window objects: all data variables belong to window objects.

Example

// window.carName can be used here
 
function myFunction() {
     carName = "Volvo";
}

 Try It! 


Do You Know?

NoteYour global variables, or functions, can override the variables or functions of the window object.
Local variables, including window objects, can cover global variables and functions.