var, let, and const in JavaScript
var, let, and const are keywords in JavaScript used to declare variables.
In every programming language, there is a way to declare variables because variables are the building blocks of any program.
Understanding variables is extremely important, especially for beginners, because they form the foundation of JavaScript.
If this foundation is not clear in the beginning, it can create confusion and problems at later stages of learning.
var
var is the earliest way to declare a variable in JavaScript. It was introduced when the JavaScript language was first created.
Variables declared using var are not block-scoped.
Let’s break this down clearly before going further.
Not block-scoped means that a variable declared using var can be accessed inside a block as well as outside the block.
On the other hand, block-scoped variables are accessible only within the block in which they are declared.
Let’s understand this with an example:
var a = 10;
{
var b = 20;
}
console.log(a + b);
Here:
ais accessible outside the blockbis also accessible outside the block
Even though b is declared inside { }, it does not stay limited to that block.
That’s why we say var is not block-scoped (often referred to as global or function-scoped).
let
The let keyword was introduced in ES6 (ECMAScript 2015).
ES6 is simply an upgraded version of JavaScript that introduced more modern and developer-friendly ways of writing code.
One of the biggest improvements introduced by ES6 is block scoping.
Now let’s understand how let works.
let a = 10;
{
let b = 20;
}
console.log(a + b);
In this case, the code will throw an error:
ReferenceError: b is not defined
This happens because let is block-scoped.
The variable b is declared inside the { } block, so it can only be accessed within that block.
Once the block ends, b no longer exists outside of it.
That’s why variables declared using let cannot be accessed outside the block in which they are defined.
const
The const keyword was introduced in ES6 to declare variables that are block-scoped.
It behaves similarly to let, but with one important difference—a variable declared using const cannot be reassigned.
Because of this, const is used to create constants, values that should not change throughout the program.
Let’s look at an example.
const pi;
If you write the above code, JavaScript will throw an error:
SyntaxError: Missing initializer in const declaration
This happens because variables declared with const must be initialized at the time of declaration.
To fix this error, you need to assign a value immediately:
const pi = 3.14;
Once declared, the value of pi cannot be changed.
