var name = "John"; var name = "Mike"; // redeclaring 'name' variable name = "David"; // reassigning 'name' variable console.log(name); // output: David
- let: It was introduced with ES6 and has a block-level scope. It can be reassigned but cannot be redeclared. A variable declared with the let keyword can be accessed only within the block it is defined in.
let name = "John"; let name = "Mike"; //SyntaxError: 'name' has already been declared name = "David"; console.log(name); //output: David
- const: It also introduced with ES6 and has a block-level scope. Once declared, its value cannot be changed. It cannot be redeclared or reassigned.
const name = "John"; name = "Mike"; //TypeError: Assignment to constant variable. const name = "David"; //SyntaxError: Identifier 'name' has already been declared console.log(name); //output: John