
JavaScript Variables: Var, Let & Const
Hey curious coder! ๐
So youโve started exploring JavaScript and bumped into these three oddballs:
var
, let
, and const
.
They all claim to help you store stuff like numbers, names, or even your deepest coding secrets ๐ต๏ธโโ๏ธ โ but how do they work? And what's the difference?
Letโs break it down like weโre at a coding party. ๐
๐ What is a Variable?
In simple words, a variable is like a box with a label.
You put something inside โ like a name or number โ and can use or change it later.
Example:
let name = "Ben";
console.log(name); // Output: Ben
Here, name
is the label, and "Ben" is the gift inside the box. ๐
Meet the Three: var
, let
, and const
They all create variables, but with different rules.
Think of them like siblings with different personalities at a dinner table:
var
โ The Old Grandpa
var age = 25;
- Used in the old days of JavaScript
- Has function scope (only cares about functions)
- Can be re-declared and updated
- Sometimes does weird things because of hoisting (explained below)
๐ Might cause confusion in big codebases โ so not recommended anymore unless you know what you're doing.
let
โ The Cool and Modern One
let city = "Delhi";
- Introduced in ES6 (a modern update of JS)
- Has block scope (respects {} like a true gentleman)
- Can be updated, but not re-declared in the same block
๐ Use this when your variable might change later (like user input, score, etc.)
const
โ The Rule Follower
const pi = 3.14;
- Also introduced in ES6
- Has block scope
- Cannot be updated or re-declared โ it's constant ๐
Use const when your value should never change (like pi, app settings, etc.)
๐คฏ Wait, Whatโs โScopeโ?
Scope decides where a variable can be used.
- Function Scope (like var): Variable lives inside a function
- Block Scope (like let and const): Variable lives inside {} like if, for, etc.
Example:
if (true) {
let food = "Pizza";
}
console.log(food); // โ Error! `food` is out of scope
๐ช Bonus: Hoisting (The Magic Trick You Didn't Ask For)
var
can be used before itโs declared โ kinda like black magic. ๐ง
console.log(x); // undefined ๐ถ
var x = 10;
But with let
and const
, this wonโt work:
console.log(y); // โ ReferenceError
let y = 20;
That's why var can be risky for beginners.
๐ So, What Should You Use?
โจ Use let
when your variable might change.
๐ Use const
when it shouldn't.
๐ Avoid var
unless you have a specific reason or are dealing with legacy code.
๐ง Final Thoughts
Variables are the building blocks of any programming language.
Think of them as your coding containers โ and now you know which container to use when!
Keep experimenting, keep building, and donโt worry if it breaks โ itโs how we learn! ๐ช
Happy Coding!
6 Reactions
0 Bookmarks