DEV Community

Laxman Nemane
Laxman Nemane

Posted on

The Differences Between let, const, and var in JavaScript.

Understanding let, const, and var in JavaScript
In JavaScript, variable declaration has evolved with the introduction of ES6 (ECMAScript 2015). Let's break down the key differences between var, let, and const, and how scoping plays a role.

1. var

Scope: Function-scoped
Variables declared with var are scoped to the function in which they are defined. If declared outside a function, they are globally scoped.
Hoisting:
var declarations are hoisted to the top of their scope, meaning they can be accessed before their declaration (though they will be undefined until the assignment).


console.log(a); // undefined
var a = 10;
console.log(a); // 10

2. let

Scope: Block-scoped
let is limited to the block in which it is defined (e.g., within {} brackets of loops or conditionals).
Hoisting:
let is also hoisted, but accessing it before the declaration results in a ReferenceError (Temporal Dead Zone).

`

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

3. const

Scope: Block-scoped

Like let, const is limited to the block in which it is defined.
Immutability:
const declarations must be initialized at the time of declaration and cannot be reassigned. However, if the variable holds an object or array, the contents can still be modified.

`

const c = 30;
c = 40; // TypeError: Assignment to constant variable.`

const obj = { key: 'value' };
obj.key = 'newValue'; // This is allowed.
console.log(obj.key); // 'newValue'

Summary

  • Use var when you need function-scoping and are working with older codebases.
  • Use let for variables that may change, especially in loops or conditional blocks.
  • Use const for variables that should remain constant, promoting immutability where possible.

Conclusion

Embrace let and const for modern JavaScript development to enhance readability and maintainability. Understanding scoping rules is crucial for writing effective and bug-free code!

Top comments (0)