DEV Community

Cover image for Mastering Variables in JavaScript: let, const, and var
Freebox
Freebox

Posted on

Mastering Variables in JavaScript: let, const, and var

If you’re starting your journey with JavaScript, one of the first things you’ll encounter is variables — the containers used to store data. Whether you’re tracking a user’s name, calculating scores in a game, or configuring settings, variables are essential.

In modern JavaScript, you have three main ways to declare them: let, const, and var. Let's break down how each one works, when to use them, and which to avoid.

What Is a Variable?

A variable is a way to label and store information so you can use it later. Think of it as a box with a name on it. Inside that box, you can keep a piece of data — like a number, a string of text, or even an entire object.

Here’s a simple example:

let city = "Berlin";
const year = 2025;
var language = "JavaScript";
Enter fullscreen mode Exit fullscreen mode

let — For Values That Change

Use let when you need to assign a value that might change later in your code.

let score = 0;
score = score + 1;
console.log(score); // 1
Enter fullscreen mode Exit fullscreen mode

Introduced in ES6 (2015), let is now the go-to choice for most variable declarations where reassignment is needed.

const — For Fixed Values

Use const when you want a variable that never changes. It makes your code more predictable and easier to debug.

const birthYear = 1940;
Enter fullscreen mode Exit fullscreen mode

Trying to reassign a const variable will cause an error:

const birthYear = 1998;
birthYear = 2000; // ❌ TypeError
Enter fullscreen mode Exit fullscreen mode

var — The old way

Before let and const, JavaScript used var. It still works, but behaves differently due to function scope and hoisting, which can lead to confusing bugs.

Example:

var mood = "happy";
Enter fullscreen mode Exit fullscreen mode

Best Practices

Use const by default.
Switch to let only when you know the value will change.
Avoid var unless absolutely necessary.
This makes your code cleaner, more readable, and less error-prone.

Mini Challenge

What do you think happens when this code runs?

let userName = "Alex";
userName = "Mia";

const country = "Belgium";
country = "China"; // ❓
Enter fullscreen mode Exit fullscreen mode

Answer:
Reassigning userName works because it was declared with let.
Trying to reassign country throws an error because it's a const.

What’s Next?

Now that you know how to store values, it’s time to learn how to do something with them.

In the next post, we’ll explore functions in JavaScript — reusable blocks of code that make your programs more efficient and organized.

Top comments (0)