May 06, 2021 JavaScript
A scope is a collection of accessible variables.
In JavaScript, you can define either global or local scopes.
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.
Variables are declared within functions, and variables are local scopes.
Local variables: Can only be accessed inside a function.
Because local variables only work within functions, different functions can use variables with the same name.
Local variables are created when the function starts executing, and they are automatically destroyed when the function is executed.
Variables are defined outside the function, i.e. global.
Global variables have a global scope: All scripts and functions in a Web page are available.
If a variable is not declared within a function (no var keyword is used), it is a global variable.
In the following example, carName is within the function, but is a global variable.
The JavaScript variable lifecycle is initialized when it is declared.
Local variables are destroyed after the function is executed.
Global variables are destroyed when the page is closed.
Function parameters only work within the function and are local variables.
In HTML, the global variable is the window object: all data variables belong to the window object.
Your global variable, or function, can override the window object's variable or function.
Local variables, including window objects, can override global variables and functions. |
In ES6, the let and const keywords are available. let is declared in the same way as var, and by declaring a variable with let instead of var, you can limit the variable to the current block of code. A constant is declared using const, whose value cannot be changed once it is set. |