JavaScript variables let you store information and use it later in your code.
A shopping website may need to store a product name, price, quantity, discount or cart total. A login form may store an email address. A menu may store whether it is open or closed.
Modern JavaScript gives you two main ways to create variables: const and let.
You may also see var in older JavaScript code. It still works, but its behavior makes it less suitable for most new code.
In this lesson, you will learn how all three work and when to use each one.
What You Will Learn
By the end of this lesson, you will know how to:
- create JavaScript variables
- use
constandlet - understand why
varis different - store strings, numbers and booleans
- change a variable value
- choose useful variable names
- understand basic variable scope
- avoid common beginner mistakes
- decide between
let,constandvar
If you have not connected JavaScript to an HTML page yet, complete the previous lesson on adding JavaScript to HTML first.
What Is a Variable in JavaScript?
A variable is a named place for a value your program needs.
For example:
const productName = "Laptop";This code stores the text "Laptop" under the name productName.
You can use that value later:
const productName = "Laptop";
console.log(productName);Output:
LaptopInstead of repeatedly writing "Laptop", your code can use productName.
That becomes much more useful when values come from forms, buttons, APIs, calculations or user actions.
Why Are JavaScript Variables Important?
Almost every useful JavaScript program works with data.
A website may need to remember:
const productName = "Laptop";
const price = 50000;
let quantity = 1;
const inStock = true;Each variable has a different job.
productName stores text.
price stores a number.
quantity stores a number that may change.
inStock stores a true-or-false value.
You will study these different kinds of values in the JavaScript Data Types lesson.
For now, focus on how the values are stored.
JavaScript Variable Syntax
The basic pattern is:
keyword variableName = value;For example:
const city = "Delhi";Here:
consttells JavaScript how the variable should behave.cityis the variable name.=assigns a value."Delhi"is the stored value.
You can also use let:
let score = 10;Or older code may use var:
var userName = "Amit";The important difference is not the stored value.
The difference is how const, let and var behave.
JavaScript const
Use const when you do not plan to assign a different value to the variable.
const websiteName = "My Website";You can use it later:
const websiteName = "My Website";
console.log(websiteName);Output:
My WebsiteIf you try to assign another value:
const websiteName = "My Website";
websiteName = "New Website";JavaScript throws an error.
That is because a variable created with const cannot be reassigned.
Use const by Default
A useful beginner rule is:
Start with
const. Useletonly when the variable needs a new value later.
For example:
const price = 500;
const taxRate = 0.18;Neither value needs to change during this example.
Using const makes that intention clear.
const Must Have a Value
This is valid:
const country = "India";This is not:
const country;A const variable must receive a value when you declare it.
JavaScript let
Use let when a variable needs to change.
Imagine a shopping cart starts with one product:
let quantity = 1;The customer adds another:
quantity = 2;Now:
console.log(quantity);outputs:
2A complete example:
let quantity = 1;
quantity = quantity + 1;
console.log(quantity);Output:
2Because quantity changes, let is the correct choice.
Real Website Example: Cart Quantity
const price = 500;
let quantity = 1;
quantity = 3;
const total = price * quantity;
console.log(total);Output:
1500Notice the choice of keywords.
price does not change, so it uses const.
quantity changes, so it uses let.
total is calculated once in this example, so it also uses const.
This is a good pattern to follow in modern JavaScript.
JavaScript var
Before let and const were added to JavaScript, developers commonly used var.
For example:
var user = "Riya";This is still valid JavaScript.
You will see var in:
- older websites
- older tutorials
- legacy code
- older JavaScript libraries
For most new beginner projects, prefer const and let.
Why Is var Usually Avoided in New Code?
var behaves differently from let and const.
One important difference is scope.
Consider:
if (true) {
var message = "Hello";
}
console.log(message);This can print:
HelloNow compare it with let:
if (true) {
let message = "Hello";
}
console.log(message);The variable is not available outside that block.
For modern code, block-based behavior is usually easier to understand and control.
You will learn scope properly in a later lesson. For now, remember:
- prefer
const - use
letwhen reassignment is needed - recognize
varwhen reading older code
let vs const vs var
| Keyword | Can reassign? | Block scoped? | Recommended for new code? |
|---|---|---|---|
const | No | Yes | Yes |
let | Yes | Yes | Yes |
var | Yes | No, it uses function scope | Usually avoid |
For beginners, this decision rule works well:
Will the variable receive a different value later?
↓
Yes No
↓ ↓
let constDo not choose let simply because it feels easier.
Using const where possible makes your code clearer.
Declaration and Assignment Are Different
Look at:
let score;This creates the variable.
That is called a declaration.
Then:
score = 10;assigns the value.
You can also do both together:
let score = 10;This declares the variable and gives it an initial value.
Reassignment
Reassignment means replacing a variable’s current value.
let score = 10;
score = 20;The variable now contains:
20You do not write let again.
Wrong:
let score = 10;
let score = 20;You are trying to declare the same block-scoped variable again.
Instead use:
let score = 10;
score = 20;Variables Can Store Different Types of Data
Variables are not limited to numbers.
String
const customerName = "Aarav";Number
const price = 999;Boolean
const isLoggedIn = true;Array
const products = ["Phone", "Laptop", "Tablet"];Object
const product = {
name: "Laptop",
price: 50000
};You do not need to understand arrays and objects yet.
The important point is that variables can refer to many kinds of JavaScript values.
The next lesson on JavaScript data types explains this in detail.
Important: const Does Not Make an Object Completely Unchangeable
This often confuses beginners.
Consider:
const product = {
name: "Laptop",
price: 50000
};You cannot do this:
product = {
name: "Phone"
};That attempts to assign a new value to the product variable.
But you can change a property inside the existing object:
product.price = 45000;
console.log(product.price);Output:
45000Likewise:
const colors = ["red", "green"];
colors.push("blue");works.
const prevents the variable itself from being reassigned. It does not automatically freeze the object or array stored through that variable.
You will understand this more easily after the dedicated arrays and objects lessons.
JavaScript Variable Naming Rules
A variable needs a valid name.
These work:
const name = "Riya";
const userName = "Riya";
const productPrice = 500;
const total2 = 1000;
const _status = "active";These do not:
const 2name = "Riya";
const user-name = "Riya";A JavaScript variable name cannot begin with a number.
A hyphen is interpreted as the subtraction operator.
JavaScript Is Case-Sensitive
These are different variables:
const userName = "Riya";
const username = "Amit";JavaScript treats uppercase and lowercase letters as different characters.
So:
console.log(userName);and:
console.log(username);can produce different results.
Use camelCase for Variable Names
JavaScript commonly uses camelCase.
Example:
const firstName = "Riya";
const productPrice = 500;
const shoppingCartTotal = 1500;The first word begins with lowercase.
Each following word begins with uppercase.
Avoid unclear names such as:
const x = 500;
const a = "Laptop";
const temp1 = true;unless the short name has a clear purpose.
Prefer:
const productPrice = 500;
const productName = "Laptop";
const inStock = true;The code becomes easier to read.
Choose Names That Explain the Value
Compare:
const p = 500;with:
const productPrice = 500;The second version tells another developer what 500 means.
Good variable names reduce the amount of explanation your code needs.
Use names such as:
const customerEmail = "user@example.com";
const cartTotal = 2500;
const menuButton = document.querySelector("#menuButton");rather than vague names.
Reserved Words Cannot Be Variable Names
JavaScript uses certain words as part of its language.
For example:
const
let
if
else
return
function
classDo not try to use those keywords as variable names.
For example, this is invalid:
const if = 10;Choose a descriptive name instead.
Basic Variable Scope
Scope describes where a variable can be accessed.
You do not need to master scope yet, but you should understand one simple idea.
A variable declared inside a block with let or const belongs to that block.
if (true) {
const message = "Hello";
console.log(message);
}Inside the block, message works.
Outside:
console.log(message);it is not available.
Blocks are surrounded by:
{
}You will explore function scope, block scope and closures later in the course.
Real-World Example: Product Price Calculator
Suppose your website has:
<p>Price: ₹500</p>
<button id="increase">Add Quantity</button>
<p id="quantity">1</p>
<p id="total">₹500</p>JavaScript:
const price = 500;
let quantity = 1;
const increaseButton = document.querySelector("#increase");
const quantityText = document.querySelector("#quantity");
const totalText = document.querySelector("#total");
increaseButton.addEventListener("click", () => {
quantity = quantity + 1;
const total = price * quantity;
quantityText.textContent = quantity;
totalText.textContent = `₹${total}`;
});Several JavaScript concepts appear here.
const price = 500;The product price remains fixed.
let quantity = 1;The quantity changes when the button is clicked.
const increaseButton = document.querySelector("#increase");The button reference does not need reassignment.
Inside the click event:
quantity = quantity + 1;updates the quantity.
Then:
const total = price * quantity;calculates the new total for that click.
This is the kind of variable usage you will encounter in real frontend development.
If the DOM code is still unfamiliar, that is fine. You will study JavaScript DOM manipulation later in the course.
Another Practical Example: Menu State
A website may need to remember whether its navigation menu is open.
let menuOpen = false;When the user opens it:
menuOpen = true;When it closes:
menuOpen = false;Because the state changes, let is appropriate.
A fixed menu element reference can use const:
const menu = document.querySelector("#menu");This shows an important distinction:
- the menu element reference stays the same
- the menu state changes
Common Beginner Mistakes With JavaScript Variables
Using let for Everything
This works:
let name = "Amit";But if name never receives another value, prefer:
const name = "Amit";Start with const.
Move to let only when reassignment is required.
Trying to Reassign const
Wrong:
const price = 500;
price = 600;If the value must change, use:
let price = 500;
price = 600;Declaring the Same let Variable Twice
Wrong:
let quantity = 1;
let quantity = 2;Use reassignment:
let quantity = 1;
quantity = 2;Using a Variable Before Creating It
Avoid:
console.log(productName);
const productName = "Laptop";For beginner code, declare the variable before you use it:
const productName = "Laptop";
console.log(productName);That keeps the program easier to follow and avoids confusing declaration-timing behavior.
Misspelling the Variable Name
const productPrice = 500;
console.log(productprice);productPrice and productprice are different names.
Use consistent capitalization.
Putting Quotes Around a Variable Name
Consider:
const name = "Riya";This:
console.log(name);prints the stored value.
This:
console.log("name");prints the literal word:
nameQuotes change the meaning.
Using var Because an Old Tutorial Uses It
You may find:
var name = "Amit";in older tutorials.
Do not assume var is required.
For new code:
const name = "Amit";or:
let name = "Amit";will usually be the clearer option.
Best Practices for JavaScript Variables
Use const unless you know the variable needs reassignment.
Use let for values that genuinely change.
Choose names that explain the stored value.
Prefer:
const shippingCost = 100;over:
const x = 100;Keep related naming consistent:
const productName = "Laptop";
const productPrice = 50000;
const productStock = 8;Declare variables close to where they are needed.
Avoid creating unnecessary global variables.
Do not use var in new beginner projects unless you are specifically learning how older JavaScript behaves.
Beginner Exercise
Create three variables:
const name = "Your Name";
const city = "Your City";
let score = 0;Print them:
console.log(name);
console.log(city);
console.log(score);Then change:
score = 10;and print it again.
Your output should end with:
10Now answer these questions yourself:
- Why are
nameandcityusingconst? - Why is
scoreusinglet? - What happens if you try to reassign
name?
Test the code instead of only guessing.
Challenge Exercise
Create variables for a product:
const productName = "Keyboard";
const price = 1500;
let quantity = 2;Calculate the total:
const total = price * quantity;Print a sentence like:
2 Keyboard items cost 3000Then change:
quantity = 3;Calculate the new total and print the updated result.
Extra Challenge
Create:
const discount = 200;Calculate:
price × quantity - discountTry to complete the calculation yourself.
Frequently Asked Questions
What is a variable in JavaScript?
A JavaScript variable is a named reference used to store or access a value such as text, a number, a boolean, an array or an object.
Should I use let or const?
Use const when the variable does not need reassignment.
Use let when you know the variable will receive a different value later.
Should I still use var?
You should understand var because you will see it in older JavaScript code. For most new code, const and let provide clearer behavior.
Can a const value change?
The variable cannot be reassigned.
However, objects and arrays assigned to a const variable can still have their contents changed unless you take additional steps to prevent that.
Can I create a let variable without a value?
Yes.
let score;You can assign it later:
score = 10;Can I create a const without a value?
No.
A const declaration requires an initial value.
const score = 10;Are JavaScript variable names case-sensitive?
Yes.
userName and username are different identifiers.
What is the difference between declaration and assignment?
Declaration creates the variable:
let score;Assignment gives it a value:
score = 10;You can also declare and assign in one statement:
let score = 10;Why is const preferred in modern JavaScript?
It clearly communicates that the variable should not be reassigned. This can make code easier to understand and reduce accidental value changes.
Summary
JavaScript variables store values your program needs.
Modern JavaScript mainly uses:
constand:
letUse const when the variable should not be reassigned.
Use let when its value needs to change.
You may still see:
varin older JavaScript, but it has different scope and redeclaration behavior.
You also learned:
- how to declare variables
- how assignment works
- how reassignment works
- basic naming rules
- camelCase naming
- basic block scope
- why
constobjects can still change internally - common variable mistakes
Understanding variables is essential because every later JavaScript topic works with values.
Continue the JavaScript Course
Previous Lesson: How to Add JavaScript to HTML: Internal, External and defer
Course Home: JavaScript Tutorial for Beginners: Learn JavaScript Step by Step
Next Lesson: JavaScript Data Types Explained for Beginners
In the next lesson, you will learn why "Hello", 25, true, null and objects are different kinds of JavaScript values, how to check a value’s type, and why data types matter when your code performs calculations, comparisons and other operations.
