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 variables, objects, and functions you have access to.
JavaScript function scope: Scope is modified within functions.
JavaScript Local Scope
Variables declared within a function are local variables and have local scope.
Local variables: Can only be accessed within the function.
Example
// carName variable cannot be called here
function myFunction() {
var carName = "Volvo";
// carName variable can be called here
}
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 are automatically destroyed when the function is completed.
JavaScript Global Variables
Variables defined outside a function are global variables.
Global variables have global scope: They can be used by all scripts and functions on the web page.
Example
var carName = " Volvo";
// carName variable can be called here
function myFunction() {
// carName variable can be called here
}
If a variable is not declared inside a function (without the var keyword), it is a global variable.
In the following example, carName is a global variable inside the function.
Example
// carName variable can be called here
function myFunction() {
carName = "Volvo";
// carName variable can be called here
}
JavaScript Variable Lifecycle
JavaScript variables are initialized when they are declared.
Local variables are destroyed after the function is executed.
Global variables are destroyed when the page is closed.
Function Parameters
Function parameters are only effective within the function and are local variables.
Global Variables in HTML
In HTML, global variables are part of the window object, so the window object can access local variables within functions.
Note: All data variables belong to the window object.
Example
// window.carName can be used here
function myFunction() {
carName = "Volvo";
}
Did You Know?
| | Your global variables or functions can override window object variables or functions. <br>Local variables, including those of the window object, can override global variables and functions. | | --- | --- |