July 13, 2019

What is the Difference between var and let in JavaScript?

var is a function-scoped. It can be re-declared.
let is a block-scoped. It can be used in for loops, while loops, if blocks. It cannot be re-declared.


Best Practice:
Do not use var in for/while loop, because after the loop, it will hold the value due to it’s availability.
var can be considered to be defined a global variable in the function scope.



var keyword
Variables declared with the var keyword can not have Block Scope.
Variables declared inside a block {} can be accessed from outside the block.
Variables can be referred to before the declaration.

Example1:

  var x = 2; 
}
// x CAN be used here

Example2:
document.write( x );//undefined
var x = 9;
document.write( x );//9

let keyword
Variables declared with the let keyword can have Block Scope.
Variables declared inside a block {} cannot be accessed from outside the block.
Variables cannot be referred to before the declaration.
Example1:

  let x = 2;
}
// x can NOT be used here

Example2:
document.write( x );//throw an error
let x = 9;
document.write( x );//9

No comments:

Post a Comment