What is the Difference between var and let in JavaScript?

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