// Simple variable declared globally var simpleGlobal = "Simple varibale declared globally"; // Variable not declared so belongs to its global scope notDeclaredGlobal = "Not declared globally so treated as global scope"; function foo() { // Variable not declared so belongs to its global scope notDeclaredInsideFunction = "Not declared inside function so treated as global scope"; // Variable is defined in global scope when assigned as window property window.anyWindowGlobalProperty = "Global variable defined as window property"; alert("Inside function"); alert(simpleGlobal); alert(notDeclaredGlobal); alert(notDeclaredInsideFunction); } foo(); alert("Outside function"); // Below alert is only valid if foo(where notDeclaredInsideFunction get declared automatically) is called. alert(notDeclaredInsideFunction); alert(anyWindowGlobalProperty)

var i; for(var i=0;i<5;i++) { var j = 5; } alert("i="+i); // prints 5 alert("j="+j); // prints 5











var name = "Saurab"; function showName () { var name = "Parakh"; // local variable that is only accessible in this this function console.log (name); // Parakh } console.log (name); // prints Saurab as resembles the global variable

var name = "Saurab"; function foo() { var name = "Kumar"; var newFun = function() { var name = "Parakh"; alert(name); //alerts Parakh i.e local and innermost }; newFun(); alert(name); //alerts Kumar i.e innermost in current scope } foo(); alert(name); //alerts Saurab which is only visible

function foo() { alert("Hi") var name = "Saurab"; }

function foo() { var name; alert("Hi"); name = "Saurab"; }

foo(); // valid call because hoisted function foo() { alert("Inside function foo") }

function foo() { alert("Inside function foo") } foo();

var num = 100; foo(); function foo(){ // This prints "undefined", because aNumber is also defined locally below. document.write(num); if (false) { var num = 123; } }

var num = 100; foo(); function foo(){ var num; // This prints "undefined", because aNumber is also defined locally below. document.write(num); if (false) { num = 123; } }

var a = 4; for (var i = 0; i < 7; i++) { let j = i+1; console.log(j); } console.log(j); // will throw ReferenceError: j is not defined

function example(x) { console.log(y); // ReferenceError: y is not defined if (x) { let y = 5; } }

for

var a; // a === undefined const b; // SyntaxError: const declarations must have an initializer

const b = 10; // b === 10 b = 20; // SyntaxError: Assignment to constant variable

Most of the people assume that scope of variable in Javascript is very much similar to other programming languages like Java and C. But there are a number of points where the behavior is different and very complex. Not only beginners, even few experienced Javascript programmers find it difficult to understand scope of variable in Javascript. These points are to be understood well to master Javascript and code with less syntactical as well as logical errorsThe scope of a variable is the portion of the program code for which the variable's name has meaning and for which the variable is said to be "visible". Javascript has two types of scopes global and local(function) level scope. Variables declared globally that are visible throughout the javascript program come under global scope. Variables declared inside functions, may have same name as global varibles, are accessible only within that function are local variables.Before we start I would like to mention a set of important points where Javascript behaves differently. I will discuss on all these points later in this article.1) No block level scope(except a special case - Block-scoped variables)2) Variables are hoisted (variables declaration are moved to top and then run)3) Chaining of scopes. Any function defined within another function has a local scope which is linked to the outer function.Any variable declared globally or in simple terms any variables declared outside functions are termed as global variables. Also any property assigned to window object is also treated as global variable. It is because in browsers, all global variables are properties of the window object. In Javascript it is not mandatory to declare variables with var keyword. If variables are defined without var(no var) outside functions, they are treated as global variable. "no var" variable definition inside function will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it).But there is a significant difference between variable declaration with var and "no var" declaration apart from its automatic global scope access.Here is a link that has a very good explanation to this difference Let us take an example.In above exampleis declared as global variable.is a "no var" variable so it is also treated to be in global scope.is another "no var" variable inside function so browser will look up for the declaration in the scope chain but when not found it will also be treated to be in the global scope. But this gets only declared when this function is called. So if we usewithout calling the function foo then it will give error stating thatis not defined.is a property assigned toobject so it will also be a global property.Javascript do not have block level scope. Here is an example.Both variablesandare visible outside the for loop. It is because block level scope is not considered in Javascript. So both these variable are visible in the current scope i.e global scope. Also variabledeclared twice so both being the global scope later one overrides the former one.JavaScript has function-level scope. Variables declared within a function are local variables and are only accessible within that function or by functions inside that function. Javascript uses scope chains to establish the scope for a given function. Each function defined has its own nested scope. Any function defined within another function has a local scope which is linked to the outer function. It's always the position in the source that defines the scope. When resolving a variable, javascript starts at the innermost scope and searches outwards.Here in above example there are two variables. Variablewithin functionis local to this function so the value of this is only visible within this function. Outside function boundaries global variable name is accessed.Also you can notice that the local variable has higher priority than variable from outer scope. Lets see another example to be more clear.In above example we noticed that in case of mutiple varibles with same name, the one which is innermost and local in the current scope is given the highest priority. Here in function, "Parakh" gets printed as it is the value of the innermost name variable.Also as discussed earlier, if the variable is not declared within the function than it belongs to the global scope.Function and variable declarations are moved to the top of their current scope i.e hoisted automatically by the Javascript interpreterLets take an example.is actually interpreted like this:So the variable name declaration is actually hoisted(moved to the top). The assignment portion remains at it its original place as shown in above example.Lets see how function declaration are hoisted.is hoisted toIn case of function declarations, the entire function body is hoisted. Here theis called before theis declared. But it works good as it is hoisted by Javascript interpreter.There can be some confusing cases too where variable with same is hoisted. Lets take another example.When JavaScript executes a function, it first looks for all variable declarations, for example,. It creates the variables with an initial value of undefined. If a variable is declared with a value, for example,;, then it still initially has the value undefined and takes on the declared value only when the line that contains the declaration is executed. In above example num prints undefined. That is because we have a local variable num with the same name and that gets hoisted.So resultant code will look something like this.ECMAScript 6 introduces support for block-scoped variables in the form of let and const.For these variables, the braces {. . .} define a new scope. When you set one of these variables to a particular value, the value applies only to the scope in which it is set.The following example illustrates the use of let and block-scoping.In above examplestatement defines a new scope with braces. So variableoutside the for loop throwsAlso block-scoped variables defined withstatement are not hoisted. Let us take another example to understand this.In the above example use of variablethrows error stating variableis not defined as variableis defined later in the code usingstatement. This is beacause of a change to the specification of block statements in ES6 which means that each block has its own lexical environment. In the above example, a new lexical environment is created when the block (the body of thestatement) is evaluated.Similarly we can also declare block-scope variables by usingstatement which actually declares constants. Here is an example to understand the behaviorVariables defined usingstatement must have an initializer. Variablein above example throws similar error while we tried to declare it without initial value.Initial value of avariable cannot be modified. Block scoped variables defined withandhave similar behavior except to the fact that variables declared withare read only and they must have an initializer while declaration.It is very good practice to always declare and define your variables rather than depending on Javascript behaviour to get the variable(no var) automatically defined in the global scope. This may lead to a very confusing code in near future when the size grows.Also always declare your variables on the top of your current scope. Do not declare a lot of global variables. Always give preferences to local variable wherever possible.Hope you liked reading my post. I would love to get your valuable feedback in for of of comments.Happy coding!