Labs ICT
Pro Login

JavaScript Variables Explained: var vs let vs const

JavaScript Concepts Explained 5 min read

A clear comparison of var, let, and const in JavaScript. When to use each one and why it matters.

JavaScript Variables Explained: var vs let vs const

Variables are fundamental to any programming language. They’re like labeled boxes that store values you can use later. JavaScript offers three ways to declare variables: var, let, and const. Understanding their differences is crucial for writing clean, bug-free code.

What Are Variables?

Think of variables as containers with names. You can put values in them, change those values, and use them throughout your code. Here’s a simple example:

let userName = "Alice";
const age = 25;
var isActive = true;

var: The Old Way

var was the original way to declare variables in JavaScript. It’s function-scoped, which means it’s visible throughout the entire function where it’s declared.

function example() {
  var x = 10;
  if (true) {
    var x = 20; // Same variable! This overwrites the first x
    console.log(x); // 20
  }
  console.log(x); // 20 (not 10 as you might expect)
}

var variables are also hoisted, meaning they’re moved to the top of their scope during compilation. This can lead to unexpected behavior.

let: The Modern Choice

let was introduced in ES6 and is block-scoped. A block is anything between curly braces {}. This makes let much more predictable than var.

function example() {
  let x = 10;
  if (true) {
    let x = 20; // Different variable! This x is only in this block
    console.log(x); // 20
  }
  console.log(x); // 10 (unchanged)
}

let can be reassigned but not redeclared in the same scope.

const: For Constants

const is also block-scoped but cannot be reassigned after initialization. It’s perfect for values that shouldn’t change.

const PI = 3.14159;
PI = 3; // Error: Assignment to constant variable

const user = { name: "Alice" };
user.name = "Bob"; // This works! You can modify object properties
user = {}; // Error: Assignment to constant variable

When to Use Each

Here’s a simple guide:

  • Use const by default for values that won’t be reassigned
  • Use let when you need to reassign a variable
  • Avoid var in modern JavaScript — it’s rarely needed
// Good practice
const API_KEY = "abc123";
let counter = 0;

// Bad practice
var oldWay = "avoid this";

Note:

In modern JavaScript development, it’s recommended to use let and const instead of var. const should be your default choice, using let only when you need to reassign a variable. This approach leads to more predictable and maintainable code.

Common Mistakes

Beginners often make these mistakes:

  1. Using var out of habit when let or const would be better
  2. Trying to reassign a const variable
  3. Confusing block scope with function scope

Understanding these differences will help you write cleaner, more reliable JavaScript code. As you practice, using let and const will become second nature.