The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value. Variables declared with var can be reassigned and redeclared in the same scope.
var name = 'Devkode'; // Global Scope
function greet() {
var message = 'Hello!!'; // Function Scope
console.log(name); // Output: Devkode
}
greet();
console.log(name); // Output: Devkode
console.log(message); // Output: Uncaught ReferenceError: message is not defined
{
var greet = 'Hey!!';
console.log(greet); // Output: Hey!!
}
console.log(greet); // Output: Hey!!
The let statement declares a block-scoped local variable, optionally initializing it to a value. Variables declared with let can be reassigned, but can’t be redeclared in the same scope.
{
let greet = 'Hey!!';
console.log(greet); // Output: Hey!!
}
console.log(greet); // Output: Uncaught ReferenceError: greet is not defined
Constants are block-scoped, much like variables defined using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared.
const greet = 'Hey!!';
greet = 'Hello!!';
console.log(greet); // Output: Uncaught TypeError: Assignment to constant variable.
Just because a variable is declared with const doesn’t mean it’s immutable, all it means is the value can’t be re-assigned.
const greet = {
message: 'Hey!!'
}
greet.message = 'Hello!!';
console.log(greet.message); // Output: Hello!!
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. So var variables are hoisted to the top of its scope and initialized with a value of undefined.
console.log(greet); // Output: undefined
var greet = 'Hey!!';
Just like var, let and const declarations are also hoisted to the top. Unlike var which is initialized as undefined, but the let and const keyword are not initialized. So if you try to use a let or const variable before declaration, you'll get a Reference Error.
It will only get initialised when the let and const statements are evaluated, everything before (above) that is called the temporal dead zone.
console.log(greet); // Output: Uncaught ReferenceError: greet is not defined
let greet = 'Hey!!';
var | let | const | |
---|---|---|---|
Scope | global or function | block | block |
redeclare? | yes | no | no |
reassign? | yes | yes | no |
hoisted? | yes | no | no |