Member-only story

var, let, and const

Sumit kumar Singh
4 min readMar 20, 2023

var, let, and const are keywords used in JavaScript for declaring variables. While all of them are used for variable declaration, they differ in terms of scope, hoisting, and mutability.

var

var is the oldest keyword for declaring variables in JavaScript. It has function-level scope, which means that a variable declared with var is accessible within the function in which it is declared, as well as any nested functions. Variables declared with var are also hoisted to the top of their scope, meaning that they are moved to the top of the code block in which they are declared. However, they are not initialized to a value until the line of code where the variable is actually declared is reached. This can sometimes lead to unexpected behavior, as a var variable can be accessed before it is initialized.

function example() {
var x = 1;
if (true) {
var x = 2; // same variable as the one declared in the function scope
console.log(x); // Output: 2
}
console.log(x); // Output: 2
}

example();

In the above example, var is used to declare the variable x with a value of 1. Within the if block, var is used again to redeclare x with a value of 2. This is possible because var variables have the function-level scope and can be accessed and modified within nested blocks.

let

--

--

Sumit kumar Singh
Sumit kumar Singh

Written by Sumit kumar Singh

YouTube: https://shorturl.at/8zZ4B Topmate: https://topmate.io/sumit_kr_singh 📚 HTML, Angular, React, and JavaScript 🧑‍💻 Tips & tricks

No responses yet