The var, let & const Confusion Every JavaScript Beginner Hits
Variables are where JavaScript starts to feel real. Let’s understand var, let, and const in simple words, with practical examples beginners can actually use.

Every programming language has a few topics that look small from outside but quietly control everything you write later. In JavaScript, variables are one of those topics.
When beginners start learning JavaScript, they usually think variables are just boxes where we store values. That explanation is not wrong. It is actually a good starting point. But after a few days, confusion starts: why do we have var, let, and const? Why does one variable work outside a block and another one does not? Why can I change an object declared with const? Why does JavaScript sometimes behave like it already knows a variable before the line has even run?
If you have had these questions, good. That means you are not just copying code. You are trying to understand how JavaScript thinks.
I have worked on enough React.js, Next.js, and JavaScript-heavy production codebases to say this honestly: variables are not a beginner-only topic. The way a team uses variables affects readability, bugs, refactoring, component state, API handling, and even how confident another developer feels while touching your code.
Sach bolo, many JavaScript bugs do not start with complicated architecture. They start with one innocent-looking variable being used in the wrong place.
First, What Is A Variable In JavaScript?
A variable is a name we give to a value so we can use that value later. Instead of repeating the same value again and again, we store it behind a meaningful name.
Think of it like keeping things on your desk. You may have a notebook for meeting notes, a water bottle, and a laptop charger. You do not call them item one, item two, item three every time. You give them names because names make life easier.
JavaScript variables do the same thing. They help us label values.
let userName = 'Siddhant';
console.log(userName); // SiddhantHere, userName is the variable name, and Siddhant is the value stored inside it.
In real frontend development, variables are everywhere: user names, API responses, button states, theme settings, cart totals, form errors, route params, loading flags, and thousands of tiny values that make an app feel alive.

Why JavaScript Has var, let, And const
In the beginning, JavaScript had var. That was the old way to create variables. Later, modern JavaScript introduced let and const because var had some behavior that often created confusing bugs.
So today we have three keywords:
var: the old variable keyword
let: a modern keyword for values that can change
const: a modern keyword for values that should not be reassigned
The var Keyword: The Old Habit That Still Exists
var is the original way of declaring variables in JavaScript. You will still see it in old tutorials, legacy projects, older libraries, and sometimes in production code that has been around for many years.
var score = 10;
score = 20;
console.log(score); // 20The problem with var is not that it never works. The problem is that it is too relaxed. It allows patterns that can become difficult to track in larger applications.
var can be redeclared
With var, you can declare the same variable again in the same scope.
var status = 'loading';
var status = 'success';
console.log(status); // successIn real projects, silent acceptance is not always a gift. Sometimes you want the language to stop you before you accidentally overwrite something important.
var is function-scoped, not block-scoped
This is where many beginners get confused. A block is usually the area inside curly braces, like an if block or a for loop. You may expect a variable created inside that block to stay inside that block.
But var does not behave that way. var is scoped to the nearest function, not the nearest block.
if (true) {
var message = 'Hello from inside the block';
}
console.log(message); // Hello from inside the blockThe variable message was created inside the if block, but it is still available outside. For beginners, this feels strange because the curly braces look like a boundary. With var, they are not a strong boundary.
Developer observation: this is one reason modern frontend teams avoid var. In React and Next.js codebases, we want variables to live close to where they are needed. var makes that harder.
When should you avoid var?
In modern JavaScript, you should usually avoid var. Not because old code using var is automatically bad, but because let and const give clearer behavior.
If you are starting today, learn var so you can understand older code, but do not make it your default habit.

The let Keyword: For Values That Need To Change
let was introduced to fix many of the practical problems developers faced with var. The simplest way to understand let is this: use let when the value is expected to change later.
let count = 0;
count = count + 1;
count = count + 1;
console.log(count); // 2This is common in real code. A counter changes. A loading flag changes. A selected tab changes. A form value changes.
let makes that intention clear: this value may be reassigned.
let is block-scoped
Unlike var, let respects block scope. If you create a let variable inside an if block, it stays inside that block.
if (true) {
let message = 'Hello from inside the block';
}
console.log(message); // ReferenceError: message is not definedThis is a good thing. JavaScript is protecting you from using a variable where it should not exist.

let cannot be redeclared in the same scope
With let, JavaScript will stop you if you try to declare the same variable name again in the same scope.
let userRole = 'author';
let userRole = 'admin'; // SyntaxErrorIn team projects, this kind of guard matters. You may not remember every variable name in a file. The language gives you a small safety net.
A frontend example with let
Imagine a simple cart total calculation. The total starts at zero and changes as we loop through items.
const cartItems = [
{ name: 'Keyboard', price: 2500 },
{ name: 'Mouse', price: 900 },
{ name: 'USB Cable', price: 300 }
];
let total = 0;
for (const item of cartItems) {
total = total + item.price;
}
console.log(total); // 3700Here, total is a good use of let because its value changes during the loop.
Developer tip: if you declare something with let but never reassign it, ask yourself whether it should be const instead. This one habit improves code clarity immediately.
The const Keyword: For Values You Do Not Reassign
const is the keyword I use the most in modern JavaScript. It means the variable binding cannot be reassigned.
const appName = 'Dev Diaries';
console.log(appName); // Dev DiariesIf you try to assign a new value to appName, JavaScript will throw an error.
const appName = 'Dev Diaries';
appName = 'Tech Notes'; // TypeErrorThis is useful because many values in code should not be reassigned. Configuration values, imported helpers, API endpoint names, component props, static arrays, and function references are often good candidates for const.
const does not mean the value is deeply frozen
This is one of the biggest beginner confusion points. const prevents reassignment of the variable itself. It does not always prevent changing the inside of the value.
For primitive values like strings and numbers, this feels simple because you cannot change the inside of a string or number. But objects and arrays are different.
const user = {
name: 'Siddhant',
role: 'developer'
};
user.role = 'senior developer';
console.log(user);
// { name: 'Siddhant', role: 'senior developer' }This works because we did not reassign user to a new object. We changed a property inside the same object.
const user = { name: 'Siddhant' };
user = { name: 'Rahul' }; // TypeErrorThat difference is very important: mutation means changing the inside; reassignment means pointing the variable name to a new value.

const with arrays
Arrays behave the same way. You cannot reassign the array variable, but you can modify the array contents.
const skills = ['JavaScript', 'React'];
skills.push('Next.js');
console.log(skills); // ['JavaScript', 'React', 'Next.js']But this will fail:
const skills = ['JavaScript', 'React'];
skills = ['Node.js']; // TypeErrorImportant note: in React development, we usually avoid mutating arrays and objects directly when they are part of state. React depends on new references to detect changes cleanly. So even though const allows array mutation, React best practice often prefers creating a new array.
const skills = ['JavaScript', 'React'];
const updatedSkills = [...skills, 'Next.js'];
console.log(updatedSkills);
// ['JavaScript', 'React', 'Next.js']This is one of those places where JavaScript knowledge and frontend framework habits meet. The language allows mutation, but your framework may reward immutability.
Scope Basics In Simple Words
Scope means where a variable is available in your code. You can think of scope like access permission.
Global scope
A variable declared outside functions and blocks is generally available globally in that file or environment.
const websiteName = 'Dev Diaries';
function printWebsiteName() {
console.log(websiteName);
}
printWebsiteName(); // Dev DiariesGlobal values can be useful, but too many global variables make code harder to maintain. In production codebases, we try to keep values close to where they are used.
Function scope
A variable declared inside a function is available inside that function.
function greetUser() {
const name = 'Siddhant';
console.log('Hello ' + name);
}
greetUser();
console.log(name); // ReferenceErrorThe name variable belongs to greetUser. Outside the function, it does not exist.
Block scope
A block is code inside curly braces. let and const respect block scope.
const isLoggedIn = true;
if (isLoggedIn) {
const welcomeMessage = 'Welcome back!';
console.log(welcomeMessage);
}
console.log(welcomeMessage); // ReferenceErrorThis keeps variables clean and prevents accidental usage outside their intended area.
Hoisting Explained Without Making It Scary
Hoisting is one of those JavaScript words that sounds more dramatic than it needs to be.
In simple words, before JavaScript runs your code, it prepares memory for declarations. That preparation behavior is called hoisting.
The confusing part is that var, let, and const do not behave exactly the same during this preparation phase.
var and hoisting
console.log(age); // undefined
var age = 30;JavaScript knows age exists, but the value is not assigned yet. So it prints undefined instead of throwing an error.
This can hide bugs. You may think the variable has a real value, but it only exists as undefined at that moment.
let and const hoisting
console.log(age); // ReferenceError
let age = 30;let and const are also technically hoisted, but you cannot use them before the declaration line. This protected area is often called the temporal dead zone. You do not need to memorize the term on Day 1, but understand the behavior: declare first, use later.

Developer tip: do not write code that depends on hoisting. It may feel clever, but clever code is not always kind code. Future you has to read it again.
Reassignment vs Redeclaration
These two words sound similar, but they mean different things.
Reassignment means changing the value of an existing variable.
let theme = 'light';
theme = 'dark';
console.log(theme); // darkRedeclaration means declaring the variable again using a keyword.
var theme = 'light';
var theme = 'dark'; // allowed with var
let mode = 'light';
let mode = 'dark'; // not allowed with letModern JavaScript discourages accidental redeclaration because it usually makes code harder to understand.
How I Choose Between var, let, And const In Real Projects
In modern frontend and full-stack JavaScript projects, my default order is simple: start with const. Use let only when reassignment is actually needed. Avoid var unless you are reading or maintaining older code.
This approach keeps your code honest. If something is const, another developer knows the variable will not suddenly point to a different value later. If something is let, it signals that the value may change.
const apiUrl = '/api/articles';
const pageSize = 10;
let currentPage = 1;
function goToNextPage() {
currentPage = currentPage + 1;
}apiUrl and pageSize do not need reassignment, so they are const. currentPage changes when the user moves through pagination, so it is let.
Common Beginner Mistakes
Using let everywhere
Many beginners use let for everything because it feels flexible. But too much flexibility can make code harder to trust. If a value does not need to change, use const.
Thinking const means object values cannot change
const protects reassignment, not deep object mutation. This mistake appears a lot when beginners start arrays and objects.
Using var because old tutorials use it
Old tutorials are not always wrong, but they may teach older habits. If you are learning modern JavaScript for React or Next.js, use let and const as your normal tools.
Using variables before declaring them
Do not depend on hoisting. Write code in the order humans read naturally: declare first, use after.
A Practical Frontend Example
Let us connect this to a small frontend-style example. Imagine we are preparing user display data after receiving an API response.
const user = {
firstName: 'Siddhant',
lastName: 'Sinha',
isPremiumUser: true
};
const fullName = user.firstName + ' ' + user.lastName;
let badgeText = 'Regular User';
if (user.isPremiumUser) {
badgeText = 'Premium User';
}
console.log(fullName); // Siddhant Sinha
console.log(badgeText); // Premium UserHere, user and fullName are const because they are not reassigned. badgeText is let because we start with a default value and then change it based on a condition.
This kind of thinking appears everywhere in UI development: default state, conditional labels, computed values, derived values, fallback text, feature flags, and user permissions.
Important Notes To Remember
Use const by default.
Use let when reassignment is required.
Avoid var in modern code.
let and const are block-scoped.
var is function-scoped.
const does not freeze objects or arrays.
Mutation and reassignment are different.
Declare variables before using them.
Final Thoughts
Variables look like a basic topic, but they shape how you think as a JavaScript developer. Once you understand var, let, and const properly, your code starts becoming clearer. You stop guessing why a value changed. You start reading scope more naturally. You begin to understand why modern teams prefer certain patterns.
If you are a beginner, do not rush this topic. Write small examples. Break them. Try var inside a block. Try let inside a block. Try changing an object declared with const. Open the browser console and observe what happens. That small practice will teach more than memorizing definitions.
For your next step, learn JavaScript data types, then functions, then conditions. Variables are where you store values. Data types explain what kind of values you are storing. Functions and conditions teach you what to do with them.
Take it one concept at a time. That is how real developers learn too.

