JavaScript Scope
The accessibility (visibility) of variables is determined by their scope.
JavaScript Function Scope
There are two kinds of scopes in
- Local scope
- Global scope
Function scope exists in each function creates a new scope. The visibility of these variables is determined by their scope. Variables defined within a function are not available (visible) from the outside.
Local JavaScript Variables
Variables specified inside a JavaScript function are LOCAL to that function. Function variables have function scope, which means they can only be accessible from within the function.
```javascript// code here can NOT use carNamefunction myFunction() {var carName = ‘Volvo’;// code here CAN use carName}```
Variables with the same name can be used in multiple functions because local variables are only recognized inside their functions. When a function starts, local variables are generated, and when the function ends, they are destroyed.
Global JavaScript Variables
GLOBAL is a variable declared outside of a function. The scope of a global variable is global: It is accessible to all scripts and functionalities on a web page.
```javascriptvar carName = ‘Volvo’;// code here can use carNamefunction myFunction() {// code here can also use carName}```
JavaScript Variables
In JavaScript, objects and functions are also variables. Variables, objects, and functions can be accessed from different areas of the code depending on their scope.
Automatically Global
If you assign a value to an unnamed variable, it becomes a GLOBAL variable. Even if the value is assigned within a function, this code sample will declare a global variable carName.
```javascriptmyFunction();// code here can use carNamefunction myFunction() {carName = ‘Volvo’;}```
Strict Mode
All modern browsers support JavaScript in “Strict Mode”. Undeclared variables are not immediately global in “Strict Mode”.
Global Variables in HTML
The global scope in JavaScript refers to the entire JavaScript environment. The window object is the global scope in HTML. The window object owns all global variables.
```javascriptvar carName = ‘Volvo’;// code here can use window.carName.```
It’s best not to create global variables unless you know what you’re doing. Window variables can be overwritten by global variables (or functions) (or functions). Your global variables and functions can be overwritten by any function, even the window object.
The Lifetime of JavaScript Variables
A JavaScript variable’s lifetime begins when it is declared. When the function is finished, the local variables are removed. When you close the browser window in a web browser, global variables are erased (or tab).
Function Arguments
Inside functions, function arguments (parameters) act as local variables.
Resources
You may find the following resources useful: