JS Variables Guide How to Declare and Use Them
Learn the three steps of working with JavaScript variables: declaring them with let or const, assigning values, and using them in expressions and function calls.
To declare JavaScript variables and use them, you do three things: declare the variable, assign it a value, and then use that value by referencing its name. This guide walks through each step with practical examples you can run yourself.
let city = "Tokyo";
console.log("I live in " + city);The first line does two things at once: the let keyword declares the variable city, and the equals sign assigns the starting value "Tokyo". The second line reads the value by using the variable name inside a string concatenation. Every variable you write follows this same three-step pattern: declare, assign, use.
Step 1: Declare a Variable
Declaring a variable tells JavaScript to reserve a named slot in memory. You use the let or const keyword, followed by the name you want to give the variable.
let username;
const maxAttempts = 3;The first line creates a variable called username that is ready for a value later. The second line creates a variable called maxAttempts that must have a value immediately and cannot be changed afterward. This is the core difference between let and const: let is flexible, const is locked.
Without a declaration keyword, JavaScript either creates an accidental global variable or throws an error in strict mode. Always start every variable with let or const to avoid these problems. This example shows the wrong way that you must avoid:
// Wrong: missing let or const
score = 10;Modern JavaScript modules enable strict mode automatically, so an undeclared assignment like this will throw a ReferenceError. The error message will point you directly to the line where the keyword is missing. This is one of the many safety improvements modern JavaScript provides over the older, looser var style.
If you are not sure which keyword to pick, start with const. Switch to let only when you discover the value needs to change later. This default makes your intent clear and prevents accidental reassignments that could introduce bugs.
Step 2: Assign a Value
Once a variable is declared, the next step is to put a value into it using the equals sign. The equals sign is the assignment operator, and its job is to store the value on the right side into the variable on the left side. This is not the same as mathematical equality. It is a storage operation that replaces whatever was in the variable before:
let fruit;
fruit = "mango";
console.log(fruit);The console prints "mango". The variable started empty, then the assignment put the string into it. You can declare and assign in one line, which is the most common pattern:
let fruit = "mango";const requires the value at declaration time. You cannot separate the declaration and assignment for a const variable. It must be given a value immediately or JavaScript will throw a SyntaxError:
const fruit = "mango"; // correct
// const fruit; // SyntaxError: missing initializer
// fruit = "mango"; // would fail even if declaration workedThis restriction is intentional. A const variable should always have a meaningful value. An undefined const would defeat its purpose.
You can assign the result of any expression, not just literal values. JavaScript evaluates the expression on the right first, then stores the result in the variable:
let sum = 5 + 10;
let fullName = "Alex" + " " + "Rivera";
let isAdult = 21 >= 18;
console.log(sum, fullName, isAdult);The console prints 15, "Alex Rivera", and true. Each variable stores the result of its expression, not the expression itself. The math, string concatenation, and comparison all happen before the assignment.
Step 3: Use the Variable
Once a variable has a value, you can use its name anywhere you need that value. The name acts as a stand-in for the data it holds.
const firstName = "Sam";
const lastName = "Chen";
const greeting = "Welcome back, " + firstName + " " + lastName;
console.log(greeting);The console prints "Welcome back, Sam Chen". The greeting variable is built by combining the other two variables with string text. Every place a value is expected, a variable name works: inside string concatenation, math expressions, function arguments, array items, and object properties.
Here is a math example where variables make the calculation readable:
let base = 100;
let tax = base * 0.08;
let total = base + tax;
console.log("Total with tax:", total);The console prints "Total with tax: 108". Each variable holds one step of the calculation. The names base, tax, and total tell you what each number means without needing comments.
This is why meaningful variable names matter.
Updating a Variable with let
Variables declared with let can change as often as needed. Each assignment replaces the previous value entirely. The old value is gone and cannot be recovered.
let counter = 1;
console.log(counter);
counter = 2;
console.log(counter);
counter = counter + 1;
console.log(counter);This prints 1, then 2, then 3. The last line is important: it reads the current value of counter, adds 1 to it, and stores the result back into counter. This read-modify-write pattern is how counters, accumulators, and state trackers work in JavaScript.
You can also use the shorthand assignment operators for common math updates. These are more concise and show the intent clearly:
let points = 10;
points += 5; // same as points = points + 5
points -= 3; // same as points = points - 3
points *= 2; // same as points = points * 2
console.log(points);The console prints 24 because 10 plus 5 is 15, minus 3 is 12, times 2 is 24. Each shorthand operator combines a math operation with assignment in one step, making the code shorter and the intent more obvious.
Reassigning vs Mutating
Reassigning a const variable is forbidden, but changing the contents of a const object or array is allowed. This distinction trips up many beginners:
| Action | const behavior |
|---|---|
| Reassign the variable to a new value | TypeError |
| Change a property on a const object | Allowed |
| Push an item into a const array | Allowed |
| Replace the entire object or array | TypeError |
Here is a concrete example that demonstrates the difference:
const user = { name: "Alex" };
user.name = "Jordan"; // allowed: mutating the object
console.log(user.name);
// user = { name: "Sam" }; // TypeError: reassignment not allowedThe console prints "Jordan". const locks the binding between the variable name and the value, not the value's contents. For primitives like strings and numbers, the entire value cannot change.
For objects and arrays, the variable always points to the same container, but you can change what is inside that container.
This means you can use const for an array and still call push, pop, or other mutating methods on it. You just cannot replace the entire array with a new one. For a more detailed comparison of these behaviors, see the let vs const guide.
Declaring Multiple Variables
You can declare several variables in one statement by separating them with commas. This works with both let and const:
let x = 10, y = 20, z = 30;
console.log(x, y, z);The console prints 10, 20, and 30. All three variables are created in a single line.
However, most style guides recommend one variable per line for readability. This makes it easier to see each variable at a glance and to add or remove variables later without reformatting:
let x = 10;
let y = 20;
let z = 30;The comma style is shorter, but the one-per-line style is easier to maintain. Pick one and be consistent throughout your file.
Common Mistakes
Using a variable before declaring it is a frequent error for beginners. Variables declared with let and const are not accessible before their declaration line. Trying to do so throws a ReferenceError:
console.log(name); // ReferenceError
let name = "Alex";Always declare variables near the top of their scope, before you use them. This avoids the temporal dead zone entirely and keeps your code easy to follow from top to bottom.
Forgetting that const blocks reassignment is another common source of errors. If you get a "TypeError: Assignment to constant variable", either switch to let or reconsider whether the value really needs to change. Often, the error reveals that you are trying to mutate something that should stay fixed.
Confusing the equals sign for assignment with the triple equals for comparison is a subtle but important distinction that beginners often mix up:
let result = 5; // assignment: puts 5 into result
if (result === 5) { // comparison: checks if result equals 5
console.log("Match");
}A single equals sign assigns. Triple equals checks if two values are equal. Mixing them up leads to bugs where you accidentally overwrite a variable instead of checking it.
Putting It All Together
Here is a complete checkout summary example. The first three lines use const for fixed inputs like item name, unit price, and quantity:
const item = "Keyboard";
const price = 75;
const quantity = 2;These values are the inputs to the calculation and should never change. The next three lines use let for values that are computed from those inputs:
let subtotal = price * quantity;
let shipping = subtotal > 50 ? 0 : 10;
let total = subtotal + shipping;Subtotal, shipping, and total are derived values that depend on the inputs. They use let because you might recalculate them later when the price or quantity changes, and each recalculation replaces the old value.
console.log("Item:", item);
console.log("Qty:", quantity);
console.log("Subtotal:", subtotal);
console.log("Shipping:", shipping);
console.log("Total:", total);The console prints the item name, quantity, subtotal of 150, free shipping of 0, and a total of 150. The const values item, price, and quantity stay fixed throughout. The let values subtotal, shipping, and total are computed from those constants.
This pattern of fixed inputs and computed outputs appears in nearly every real JavaScript program.
Now that you know how to declare and use variables, learn the full comparison of var, let, and const, and check the guide on JavaScript variable naming conventions for clearer code.
Rune AI
Key Insights
- Declare variables with let for changeable values and const for fixed values.
- Assign a value with the = operator.
- Reassign let variables anytime; const blocks reassignment.
- Use the variable name to read its value anywhere in scope.
- Never declare a variable without let or const.
Frequently Asked Questions
What happens if I declare a variable without assigning a value?
Can I change the type of value stored in a variable?
What is the best way to name variables?
Conclusion
Declaring a variable creates a named slot in memory. Assigning puts a value into that slot. Using the variable name anywhere in your code reads the current value back. These three steps are the foundation of every JavaScript program you will write.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.