A variable declared using "var" has function 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

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