JavaScript Variables: var vs let vs const

Himmat Kumar Mar 25, 2025, 5:33 PM
Blog Thumbnail

JavaScript Variables: var, let & const

Variables are the building blocks of any programming language. In JavaScript, you use them to store data, reuse values, and write clean, maintainable code. Let's break down the three ways to declare variables in JavaScript: var, let, and const.

1. What Are Variables?

A variable is like a container that holds a value — it could be a number, text, object, or more. Think of it like naming a box so you know what’s inside.

let name = "Alice";
const age = 25;
var city = "New York";

2. The Old Way: var

var was the only way to declare variables before ES6 (2015). It's function-scoped and allows redeclaration — but that can lead to bugs.

var score = 10;
var score = 20; // ✅ allowed

function testVar() {
  var x = 1;
  if (true) {
    var x = 2;
    console.log(x); // 2
  }
  console.log(x); // 2
}

3. The Better Way: let

Use let when the value of your variable might change. It’s block-scoped, so it behaves better inside loops and conditionals.

let count = 1;
count = 2; // ✅ allowed

if (true) {
  let count = 3;
  console.log(count); // 3
}
console.log(count); // 2

4. The Constant Way: const

Use const when your variable should never change. It must be assigned a value when declared and can’t be reassigned.

const pi = 3.14;
// pi = 3.14159; ❌ Error

const user = { name: "John" };
user.name = "Jane"; // ✅ allowed (object values can change)

5. Comparison Table

Feature var let const
Scope Function Block Block
Reassignable
Redeclarable
Hoisted ✅ (undefined) ✅ (TDZ) ✅ (TDZ)

6. Final Tips

  • Use const by default unless you need to reassign.
  • Use let when the value changes.
  • Avoid var unless working on legacy projects.
Remember: Better variable management = fewer bugs and cleaner code!

Comments

Please login to leave a comment.

No comments yet.

Related Posts

javascript-data-types-explained
Himmat Kumar Mar 25, 2025, 12:17 PM

JavaScript Data Types Explained with Examples

javascript-loops-for-while-do-while
Himmat Kumar Mar 29, 2025, 5:43 AM

JavaScript Loops — for, while, do...while

javascript-functions-and-scope-guide
Himmat Kumar Mar 30, 2025, 5:26 AM

JavaScript Functions & Scope

javascript-date-and-time-guide
Himmat Kumar Mar 30, 2025, 6:46 AM

Date and Time in JavaScript — Easy Guide

introduction-to-javascript
Himmat Kumar Oct 27, 2023, 11:36 AM

Introduction JavaScript