Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Scope

JavaScript Scope


Scope is the set of variables that are accessible.


JavaScript Scope

In JavaScript, objects and functions are also variables.

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

JavaScript function scope: Scope is modified inside a function.


JavaScript Local Scope

Variables declared inside a function are local variables and have local scope.

Local variables: can only be accessed inside the function.

Example

//

The carName variable cannot be used here

function

myFunction

(

)

{

var

carName

=

"

Volvo

"

;

//

The carName variable can be used inside the function

}

Try it »

Because local variables only apply inside a function, different functions can use variables with the same name.

Local variables are created when the function begins executing and are automatically destroyed after the function finishes.


JavaScript Global Scope

A variable defined outside a function is a global variable.

Global variables have Global scope: they can be used by all scripts and functions on the web page. 

Example

var

carName

=

"

Volvo

"

;

//

The carName variable can be used here

function

myFunction

(

)

{

//

The carName variable can be used inside the function

}

Try it »

If a variable is not declared inside a function (without the var keyword), it is a global variable.

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

Example

//

The carName variable can be used here

function

myFunction

(

)

{

carName

=

"

Volvo

"

;

//

The carName variable can be used here

}

Try it »


JavaScript Variable Lifetime

A JavaScript variable's lifetime is initialized when it is declared.

Local variables are destroyed after the function finishes executing.

Global variables are destroyed when the page is closed.


Function parameters

Function parameters only work inside the function; they are local variables.


Global variables in HTML

In HTML, the global variable is the window object, so the window object can call undeclared local variables inside a function (those without var).

**Note:** All global variables belong to the window object.

Example

//

window.carName can be used here

function

myFunction

(

)

{

carName

=

"

Volvo

"

;

}

Try it »


Did you know?

| Note | Your global variables or functions can override variables or functions of the window object.
Local variables, including the window object, can override global variables and functions. | | --- | --- |

In JavaScript, local variables inside a function usually cannot be accessed directly from an outer scope, but there are several ways to expose them to the outer scope, as follows: