- var: Reserved keyword
- We can't name any variable with a keyword.
- Declaration & Initialization of a variable.
- Uninitialized variable holds 'undefined' value.
Variable Hoisting: bringing the variable declaration to the top of the file.
var x; // undefined
console.log(x);
x = 10; // initialized
console.log(x);
Scoping:
- var: nearest fn block
- let, const : block scope i.e inside {} created by for(){}, if(){} etc.
- let, const : No hoisting, ReferenceError thrown.
- const: No rebinding of value will happen. TypeError thrown on attempt to reassig value.
{
var x = 10;
}
console.log(x); //10
{
let y = 20;
}
console.log(y); //ReferenceError
Reduce overwriting-reassingning variables as they can be pointing to something else and would create a debugging mess. Not favoured in functional programming style.
Difference between let & const:
let x = {
name: "TOm"
}
x = 12; //12 object gets overwritten by value 12
let y = {
name: "TOm"
}
y = 12; //TypeError, assignment to a constant variable.
const human = { name: 'Jon'};
human.name = 'Charlie'; // its not reassignment, its talking to object for mutating its properties. It allows updating the value for object.
console.log(human.name); // Charlie