JavaScript Variables: let, const and var Explained
Learn how to store and reuse data with JavaScript variables. Understand let, const and var, when to use each, and how to name variables well.
What you will learn
Programs work with information: a user’s name, a price, a score, a list of items. To use that information you need a place to keep it. In JavaScript that place is called a variable. In this lesson you will learn what variables are, how to create them with let, const and var, which one to choose, and how to give your variables good names.
What is a variable?
A variable is a named box that holds a value. You put something in the box, give the box a label, and later you can find it, read it or replace it by using the label.
Think of a water bottle with your name written on it:
- The bottle is the memory space.
- Your name on it is the variable name.
- The water inside is the value.
let city = "Delhi";
console.log(city);
Output:
Delhi
Here city is the label and "Delhi" is the value stored in it.
Creating a variable
Creating a variable has a special name: declaring. Putting a value into it is called assigning.
let age; // declare: make the box
age = 20; // assign: put 20 in the box
let year = 2026; // declare and assign in one line (most common)
The parts of let year = 2026;:
letis the keyword that says “create a variable”.yearis the name you chose.=is the assignment operator. It does not mean “equal to” here. It means “put the value on the right into the box on the left”.2026is the value.
If you declare a variable but give it no value, it holds a special value called undefined:
let nickname;
console.log(nickname);
Output:
undefined
let: a value that can change
Use let when the value will change later, such as a score in a game or a counter.
let score = 0;
console.log(score); // 0
score = 10; // change the value: no "let" this time
console.log(score); // 10
score = score + 5; // use the old value to make a new one
console.log(score); // 15
Notice that you write let only once, when you create the variable. Later you just use the name. Writing let score again in the same place gives an error:
let score = 0;
let score = 5; // SyntaxError: Identifier 'score' has already been declared
const: a value that stays the same
Use const (short for constant) when the value should never be reassigned, such as a person’s date of birth, the value of pi, or a fixed setting.
const pi = 3.14159;
const website = "MyCodeNest";
console.log(pi, website);
If you try to change a const, JavaScript stops you:
const pi = 3.14159;
pi = 3; // TypeError: Assignment to constant variable.
This is helpful, because it protects you from changing something by accident. A const must also get its value right away:
const tax; // SyntaxError: Missing initializer in const declaration
Rule of thumb: start with
const. Change it toletonly when you find out that the value really needs to change. Most variables in real code areconst.
var: the old way
Before 2015, var was the only way to create a variable. let and const were added in ES6 (a big JavaScript update) to fix problems with var.
var oldStyle = "I still work";
console.log(oldStyle);
var still works, and you will see it in old tutorials and old code, so you should be able to read it. But you should not use it in new code, because of the differences below.
Difference 1: scope
Scope means where in your code a variable can be used. let and const live only inside the block { } where they are created. var ignores blocks and leaks outside.
if (true) {
var a = "I am var";
let b = "I am let";
}
console.log(a); // "I am var" (leaked out of the block!)
console.log(b); // ReferenceError: b is not defined
The behaviour of let is what most people expect. The leaking of var causes bugs that are hard to find.
Difference 2: redeclaring
var lets you declare the same name twice without any warning, which can silently overwrite a value by mistake:
var user = "Riya";
var user = "Karan"; // no error, Riya is lost
console.log(user); // "Karan"
With let and const the same mistake gives a clear error, so you notice it.
Difference 3: using it before the declaration
console.log(x); // undefined (no error, confusing!)
var x = 5;
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 5;
With var, JavaScript quietly moves the declaration to the top (this is called hoisting) and gives you undefined. With let and const you get a clear error, which is much easier to fix. We will look at hoisting again in the scope lesson.
let vs const vs var at a glance
var |
let |
const |
|
|---|---|---|---|
| Can be reassigned | Yes | Yes | No |
| Can be redeclared in the same scope | Yes | No | No |
| Scope | Function | Block | Block |
| Must have a value when created | No | No | Yes |
| Use in new code? | No | When the value changes | By default |
A small real example
Let us calculate the price of a shopping bill:
const itemPrice = 250;
const quantity = 3;
const taxRate = 0.18;
let total = itemPrice * quantity; // 750
total = total + total * taxRate; // add tax
console.log("Total to pay:", total);
Output:
Total to pay: 885
itemPrice, quantity and taxRate never change, so they are const. total changes as we calculate, so it is let. Using the right keyword also tells the next reader what to expect.
Naming variables
Good names make code easy to read. JavaScript has strict rules and helpful conventions.
The rules (break these and you get an error)
- A name can contain letters, digits,
_and$. - It cannot start with a digit:
1stPlaceis invalid,firstPlaceis fine. - It cannot contain spaces or hyphens:
user nameanduser-nameare invalid. - It cannot be a reserved word such as
let,const,if,classorreturn. - Names are case-sensitive:
score,ScoreandSCOREare three different variables.
let userName = "Neha"; // valid
let _count = 1; // valid
let $price = 99; // valid
let 2fast = "no"; // invalid: starts with a digit
let user-name = "no"; // invalid: hyphen
let class = "no"; // invalid: reserved word
The conventions (good habits)
- Use camelCase for normal variables: the first word is small, each next word starts with a capital letter, like
firstName,totalPrice,isLoggedIn. - Use meaningful names.
priceis better thanp, andnumberOfStudentsis better thann. - Use UPPER_SNAKE_CASE for fixed values that are known before the program runs, such as
MAX_USERSorTAX_RATE. - Names of true/false values often start with
is,hasorcan:isOpen,hasAccount.
// Hard to understand
let x = 18;
let y = 500;
// Easy to understand
const legalAge = 18;
let cartTotal = 500;
Tip: Good names save you from writing comments. If you have to explain a variable in a comment, it probably needs a better name.
Assigning multiple variables
You can declare several variables in one statement, and you can copy one variable into another:
let a = 1, b = 2, c = 3; // works, but one per line is easier to read
let first = 10;
let second = first; // copies the value 10
first = 99;
console.log(first, second); // 99 10 (second is unaffected)
A note about const with arrays and objects
const means the variable cannot be pointed to something else. It does not freeze what is inside an array or an object:
const fruits = ["apple", "banana"];
fruits.push("mango"); // allowed: we changed the content
console.log(fruits); // ["apple", "banana", "mango"]
fruits = ["grape"]; // TypeError: not allowed to reassign the variable
You will understand this fully in the arrays and objects lessons. For now, just remember that const stops reassignment.
Common mistakes
- Using
letagain when changing a value. Writelet score = 0;once, then justscore = 10;. - Trying to change a
const. If you seeAssignment to constant variable, either the value really changes (switch tolet) or you have a bug. - Wrong capital letters.
userNameandusernameare different variables. A typo givesReferenceError: username is not defined. - Using a variable before it is created. With
letandconst, the line that creates the variable must come first. - Putting quotes around a variable name.
console.log("city")prints the word city.console.log(city)prints the value inside the variable. - Choosing names like
a,x1,temp2. You will not remember what they mean tomorrow. - Using
varout of habit. Useconstandlet.
Practice
-
In the editor, create a
constcalledmyNamewith your name and aletcalledagewith your age. Print both with oneconsole.log(). -
Increase
ageby 1 on the next line and print it again. Then changeagetoconstand read the error. -
Create
let coins = 100;. Subtract 30, then add 15, and printcoinsafter each step. What is the final value? -
Which of these names are invalid?
total_price,3rdItem,first name,$amount,let,_id. Try them in the editor to check. -
Predict the output, then run the code:
let a = 5; let b = a; a = 20; console.log(a, b);
Recap
- A variable is a named box that stores a value. You declare it and assign a value with
=. - Use
constby default. Useletwhen the value has to change. Avoidvarin new code. letandconstare block scoped.varleaks out of blocks and can be redeclared, which causes bugs.- A declared variable without a value is
undefined. - Names use letters, digits,
_and$, cannot start with a digit, and are case-sensitive. Use camelCase and meaningful names. constprevents reassignment, not changes inside arrays and objects.- Next you will look at the kinds of values a variable can hold: data types.