JS Variables
Variables in JavaScript and usage
In JavaScript, variables are used to store data. To create variables, the following three main keywords are used: var, let, and const.
Example:
console.log(name); // undefined
var name = 'John';
console.log(name); // 'John'
Functional Scope:
function test() {
if (true) {
var x = 10;
}
console.log(x); // 10
}
test();
Issues:
Example:
console.log(name); // ReferenceError: Cannot access 'name' before initialization
let name = 'John';
console.log(name); // 'John'
Block Scope:
function test() {
if (true) {
let x = 10;
}
console.log(x); // ReferenceError: x is not defined
}
test();
Advantages:
Example:
const name = 'John';
name = 'Jane'; // TypeError: Assignment to constant variable
Modifying Object Content:
const person = { name: 'John' };
person.name = 'Jane'; // allowed
console.log(person.name); // 'Jane'
Advantages:
Feature | var | let | const |
Block Scoping | ❌ | ✅ | ✅ |
Function Scoping | ✅ | ❌ | ❌ |
Hoisting | ✅(undefined) | ✅(ReferenceError) | ✅(ReferenceError) |
Reassignment | ✅ | ✅ | ❌ |
Initial Value Required | ❌ | ❌ | ✅ |
var is hoisted but initialized as undefined.
let and const are hoisted, but their values are not accessible until declared, resulting in a ReferenceError.
console.log(a); // undefined
var a = 5;
console.log(b); // ReferenceError
let b = 5;
console.log(c); // ReferenceError
const c = 5;
You can read more here