Javascript Scope: Example
Javascript Scope: Example
Example
// code here can not use carName
function myFunction() {
var carName = "Volvo";
// code here can use carName
}
Since local variables are only recognized inside their functions, variables with
the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the
function is completed.
A global variable has global scope: All scripts and functions on a web page can
access it.
Example
var carName = " Volvo";
// code here can use carName
function myFunction() {
// code here can use carName
}
Automatically Global
If you assign a value to a variable that has not been declared, it will
automatically become a GLOBAL variable.
This code example will declare carName as a global variable, even if it is
executed inside a function.
Example
// code here can use carName
function myFunction() {
carName = "Volvo";
// code here can use carName
}
Function Arguments
Function arguments (parameters) work as local variables inside functions.
Example
// code here can use window.carName
function myFunction() {
carName = "Volvo";
}