Saturday, November 7, 2020

JAvascript variable scope

In JavaScript there are two types of scope:

Local scope

Global scope


JavaScript has function scope: Each function creates a new scope.

Scope determines the accessibility (visibility) of these variables.

Variables defined inside a function are not accessible (visible) from outside the function.

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables have Function scope: They can only be accessed from within the function.


// 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.



var carName = "Volvo";


// code here can use carName


function myFunction() {


  // code here can also 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 a global variable carName, even if the value is assigned inside a function.



// code here can use carName


function myFunction() {

  carName = "Volvo";

}



Strict Mode

All modern browsers support running JavaScript in "Strict Mode".

With JavaScript, the global scope is the complete JavaScript environment.

In HTML, the global scope is the window object. All global variables belong to the window object.

var carName = "Volvo";

Do NOT create global variables unless you intend to.

Your global variables (or functions) can overwrite window variables (or functions).

Any function, including the window object, can overwrite your global variables and functions.


The Lifetime of JavaScript Variables

The lifetime of a JavaScript variable starts when it is declared.

Local variables are deleted when the function is completed.

In a web browser, global variables are deleted when you close the browser window (or tab).

References:

https://www.w3schools.com/js/js_scope.asp


No comments:

Post a Comment