Javascript - Variables

Mohammed Ali - Aug 18 - - Dev Community
  • 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);
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
  • 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

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .