var

A variable declared anywhere inside a function using "var" has function scope.
A variable declared using "var" is hoisted.
A variable declared using "var" can be accessed before it has been declared because the hoisting initialises it to the value "undefined".

function myFunction() { 
   var x = 100;
   if (true) {
      var x = 200;
   }
   console.log(x); // x is 200
}

This is because x has a function scope and does not have block scope.


Global scope

If the var keyword is omitted and a value is just assigned to a variable then it will have 'global scope'.
For global scope just leave off the var

var Data = "smith"; 

You can use strict mode to prevent this


Warning - Same Names

The 'var' keyword will let you redeclare a variable with the same name in the same scope.
let' and 'const' will not allow this.


Warning - Inside a For Loop

Declaring a variable with 'var' inside a for loop can be accessed from outside the for loop, infact from anywhere in that function.


Warning - Last Value that has been assigned

Scope Conflict



© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext