DEV Community

Cover image for Var vs Let vs Const
Muhammed Shameel Maravan
Muhammed Shameel Maravan

Posted on

Var vs Let vs Const

If you're new to JavaScript, you've probably come across three ways to declare variables: var, let, and const. These might seem like just different ways to do the same thing, but they have some crucial differences that can affect your code. Let's dive into the world of JavaScript variable declaration and understand when to use each one.

Var

var used to be the only way to declare variables in JavaScript until ES6 (ECMAScript 2015) introduced let and const. While var is still valid, but it comes with some quirks that make it less preferred in modern JavaScript development.

Scope: Functional

Variables declared with var have a functional scope, which means they are function-scoped. This can lead to unexpected behavior if you're not careful.

function example() {
if (true) {
var x = 10;
}
console.log(x); // Outputs 10, even though 'x' was declared inside the 'if' block.
}

Hoisting

Variables declared with var are hoisted to the top of their containing function or global scope. This means you can use them before they are declared, which can be confusing.

console.log(y); // Outputs 'undefined'
var y = 5;

let

let was introduced in ES6 to address some of the issues with var. It has a block scope, making it easier to predict where a variable is accessible.

Scope: Block

Variables declared with let are block-scoped, which means they are limited to the nearest enclosing block (usually denoted by curly braces {}).

function example() {
if (true) {
let x = 10;
}
console.log(x); // Throws an error: 'x' is not defined
}

No Hoisting

Unlike var, variables declared with let are not hoisted. You can't use them before they are declared.

console.log(z); // Throws an error: Cannot access 'z' before initialization
let z = 5;

const

const, also introduced in ES6, is used to declare constants. Once you assign a value to a const variable, you can't change it.

Scope: Block

Like let, const is block-scoped. However, the value it holds is immutable.

if (true) {
const pi = 3.14;
pi = 42; // Throws an error: Assignment to a constant variable
}

When to Use Each

Use const when you want to declare a variable that should never change its value.

Use let when you need to reassign a variable.

Avoid using var in modern JavaScript unless you have a specific reason to use it.

In modern JavaScript, it's generally recommended to use let and const because they provide better control over variable scope and immutability. This helps prevent bugs and makes your code easier to maintain.

So, remember: var is old-school, let is versatile, and const is for constants. Choose the right tool for the job to write clean and reliable JavaScript code.

Happy coding!

Top comments (0)