let Vs var Vs const in Javascript
JavaScript is a versatile and widely used programming language that offers multiple ways to declare variables, including let
, var
, and const
. Each of these declarations serves a specific purpose and has its own scope and behavior. In this blog post, we’ll dive into the differences between let
, var
, and const
in JavaScript with examples to help you understand when and how to use them effectively.
This post was originally posted at https://agrawalsuneet.github.io/blogs/let-vs-var-const-in-javascript/ and later reposted on Medium.
var — The Traditional Variable Declaration
var
is the oldest way to declare variables in JavaScript. Variables declared with var
are function-scoped, which means their scope is limited to the function they are declared in or the global scope if declared outside any function.
Example:
function exampleVar() {
var x = 10;
if (true) {
var x = 20; // This reassigns the outer 'x'
}
console.log(x); // Outputs 20
}
In the above example, the if block doesn’t create a new scope for x
, so it reassigns the outer x
to 20
.
let — Block-Scoped Variables
let
was introduced in ECMAScript 6 (ES6) to address some of the issues with var
. Variables declared with let
are block-scoped, meaning they are confined to the block (enclosed by curly braces) in which they are defined.
Example:
function exampleLet() {
let x = 10;
if (true) {
let x = 20; // This is a separate 'x' from the outer one
}
console.log(x); // Outputs 10
}
Here, the inner x
is distinct from the outer x
, thanks to let’s block-level scope.
const — Constants
const
is another ES6 addition that allows you to declare variables that cannot be reassigned after their initial value is set. Like let
, const
is block-scoped.