Var, Let and Const in JavaScript

Rukshan Ranabahu
2 min readJul 30, 2022

--

In JavaScript, var, let, and const are used to declare variables, but they have some differences in terms of scope and mutability:

  1. var: Before the introduction of let and const in ECMAScript 2015 (ES6), var was the primary way to declare variables in JavaScript. Variables declared with var have function scope or global scope, which means they are accessible throughout the entire function or globally if declared outside any function. Hoisting is also applicable to var variables, allowing them to be accessed before they are declared. Additionally, var variables can be redeclared and reassigned.
  2. let: Introduced in ES6, let allows the declaration of block-scoped variables. Variables declared with let are limited in scope to the block, statement, or expression in which they are defined. This means they are not accessible outside of that block. Unlike var, let variables are not hoisted, so you need to declare them before using them in the block. let variables can be reassigned, but they cannot be redeclared within the same scope.
  3. const: Also introduced in ES6, const is used to declare variables with block scope that are meant to be constants. Once a value is assigned to a const variable, it cannot be reassigned or redeclared within the same scope. const variables are also not hoisted and must be assigned a value at the time of declaration. It's important to note that while const prevents reassignment of the variable itself, it does not make the assigned value immutable. If the assigned value is an object or an array, its properties or elements can still be modified.

In summary, var has function scope, let has block scope and allows reassignment, while const has block scope and is used for declaring constants that cannot be reassigned. The choice between let and const depends on whether you need to change the value of the variable or not.

--

--

No responses yet