WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Scope


Scope is a collection of accessible variables.


JavaScript scope

In JavaScript, objects and functions are also variables.

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

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

Local JavaScript Variables

Variables are declared inside functions, and variables are locally scoped.

Local variables: accessible only inside functions.

Example

//the carName variable cannot be called here function myFunction () { var carName = "Volvo"; //call the carName variable inside the function }
Try it Yourself »

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

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


Global JavaScript Variables

Variables are defined outside functions, that is, global variables.

Global variables have Global scope : All scripts and functions in the webpage can be used。 

Example

var carName = "Volvo"; //call the carName variable here function myFunction () { //call the carName variable inside the function }
Try it Yourself »

If a variable is not declared inside a function (without using the var keyword), the variable is a global variable. In the following example, carName is inside the function, but is a global variable.

Example

//call the carName variable here function myFunction () { carName = "Volvo"; //call the carName variable here }
Try it Yourself »

JavaScript variable life cycle

JavaScript variable lifecycle is initialized when it is declared.

Local variables are destroyed after the function finishes executing.

Global variables are destroyed after the page is closed.


Function parameters

Function parameters work only within functions and are local variables.


Global Variables in HTML

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

Example

// use window.carName here function myFunction () { carName = "Volvo"; }
Try it Yourself »