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".
var variables are initialized with a value of undefined.
var variables can be used before they have been declared.
var variables can be re-declared within the scope.

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

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