This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to Javascript

Variables (var, let, const)

In Javascript, there are three main ways to declare variables: var, let, and const. Each has its own use case and behaves differently in terms of scope, hoisting, and mutability.

In Javascript, there are three main ways to declare variables: var, let, and const. Each has its own use case and behaves differently in terms of scope, hoisting, and mutability. Here's a breakdown:

var

Scope: var is function-scoped, meaning it is limited to the function where it's declared. If declared outside of any function, it becomes a global variable.

Hoisting: Variables declared with var are hoisted to the top of their scope, meaning they can be accessed before their declaration. However, they will be undefined until the actual line of code where they are assigned.

Re-declaration: You can re-declare a variable with var without any error.

Example:

function example() {
console.log(a); // undefined (hoisted)
var a = 10;
console.log(a); // 10
}

let

Scope: let is block-scoped, which means it is only accessible within the block (e.g., within {}) where it's declared. This makes it safer to use inside loops or conditional statements.

Hoisting: Variables declared with let are hoisted, but they are not initialized. If you try to access them before their declaration, it will throw a ReferenceError.

Re-declaration: You cannot re-declare a variable with let in the same scope. Attempting to do so will result in an error.

Example:

{
let b = 20;
console.log(b); // 20
}
console.log(b); // ReferenceError: b is not defined

const

Scope: Like let, const is also block-scoped.

Hoisting: const is also hoisted but not initialized, similar to let, and will throw a ReferenceError if accessed before declaration.

Mutability: Variables declared with const must be assigned a value at the time of declaration, and that value cannot be re-assigned. However, if the const variable holds an object or an array, the contents of the object or array can still be modified.

Re-declaration: You cannot re-declare or re-assign a const variable.

Example:

const c = 30;
c = 40; // TypeError: Assignment to constant variable
const arr = [1, 2, 3];
arr.push(4); // This is allowed because the array itself is mutable
console.log(arr); // [1, 2, 3, 4]

Summary

Use var if you need a function-scoped variable (rare in modern development).

Use let for variables that you expect to change, especially within loops or conditions.

Use const for variables that should not be re-assigned, promoting immutability.

In most modern JavaScript, let and const are preferred over var due to their clearer scoping rules and reduced chances of bugs.