JavaScript Variables Tutorial Complete Guide with Examples
Variables are named containers that store data in your code. Learn what JavaScript variables are, how to create them, and how to use them with clear examples.
JavaScript variables are named containers that store a value so you can use it later. Instead of writing the same piece of data over and over, you give it a name and refer to that name whenever you need it.
Think of a variable like a labeled box. You put something inside, write a label on it, and whenever your code needs that thing, it looks for the label. The label is the variable name, and whatever is inside is the value.
let greeting = "Hello, reader!";
console.log(greeting);The word greeting is the variable name. The string "Hello, reader!" is the value stored inside it. When the second line runs, JavaScript reads the current value of greeting and prints it to the console.
This is the simplest possible JavaScript variable: a name pointing to a piece of data.
What Variables Do
Variables solve three problems that come up in every program you write.
First, they let you store data once and use it many times. Without variables, you would copy the same value everywhere it is needed, and changing it later would mean hunting down every single copy.
Second, they give meaning to raw values. A variable named userAge tells you immediately what a number represents. A bare number 25 sitting in your code could mean anything.
Third, they track changing state. Counters, scores, form inputs, and user data all change while a program runs. A variable holds the current value at any moment in time.
Here is a small example that shows all three ideas at work:
let itemPrice = 12;
let quantity = 3;
let total = itemPrice * quantity;
console.log("Total cost:", total);Each variable stores one piece of data with a clear, descriptive name. The total variable depends on itemPrice and quantity. If you update quantity later and recalculate, you only change one number and the rest adapts automatically.
How to Declare a Variable
Declaring a variable means telling JavaScript to create a named slot in memory. You do this with the let or const keyword followed by the name you want to give it.
let username;This line creates a variable called username with no value assigned yet. JavaScript automatically gives it the default value undefined until you explicitly put something in it. You can verify this by logging the variable right after declaring it:
let username;
console.log(username);The console prints undefined because the variable exists but has not been assigned a value yet. Most of the time, you will declare and assign a value in a single step. The two-step approach is useful when the value depends on a condition that has not been checked yet.
Declaring a variable also determines where it is visible in your code, which is called its scope. Variables declared with let and const are block-scoped, meaning they only exist inside the nearest set of curly braces. This keeps variables contained and prevents accidental name collisions.
How to Assign and Reassign Values
Assigning means putting a value into a variable using the equals sign. The value on the right side gets stored into the variable name on the left side.
let score;
score = 100;
console.log(score);After this runs, score holds the number 100. The equals sign does not mean mathematical equality here. It means store the value on the right into the variable on the left.
This distinction matters because you will see assignment used repeatedly in ways that look like math but are really storage operations.
A variable declared with let can be reassigned as many times as you need. Each new assignment replaces the previous value completely:
let score = 100;
console.log(score);
score = 200;
console.log(score);The first log prints 100, and the second prints 200. The old value is gone forever, replaced by the new one. Understanding that assignment is destructive helps you avoid losing data you still need.
You can also declare and assign in one line, which is the most common pattern:
let color = "blue";
console.log(color);This creates the variable and gives it a starting value at the same time. It is cleaner than the two-step approach and avoids the temporary undefined state that can cause confusion during debugging.
const: Variables That Cannot Be Reassigned
The const keyword also creates a variable, but with one important restriction: you cannot reassign it after the initial value is set. The binding between the name and the value is permanent for the lifetime of the variable.
const maxPlayers = 4;
console.log(maxPlayers);This prints 4, just like a let variable would. The difference appears when you try to change the value later. JavaScript throws a TypeError and the program stops at that line:
const maxPlayers = 4;
maxPlayers = 5;The error message "Assignment to constant variable" tells you exactly what went wrong. You tried to change something that was declared as unchanging. This error is actually helpful because it catches a potential logic bug early, before wrong data propagates through your program.
Use const for values that should stay the same throughout your program: configuration limits, fixed math values like tax rates, or references to DOM elements that you want to keep pointing at the same thing. For a detailed guide on when to pick const over let, see the let vs const comparison.
Variable Naming Rules
JavaScript enforces a few rules for what counts as a valid variable name. The name must start with a letter, underscore, or dollar sign. After the first character, you can also use digits.
Spaces, hyphens, and most special characters are not allowed.
Here are the rules in a quick reference table:
| Rule | Valid examples | Invalid examples |
|---|---|---|
| Start with a letter, underscore, or dollar sign | name, _count, $price | 1stPlace, @user |
| Only letters, digits, underscore, dollar sign | userName2, total_cost | user-name, first name |
| Cannot be a reserved keyword | user, item | let, const, function, class |
| Case-sensitive | score and Score are different |
Stick to camelCase for most variable names: firstName, totalPrice, isLoggedIn. This is the universal convention in JavaScript and makes your code immediately readable to other developers.
Variable names should also be descriptive, not cryptic. A name like x tells you nothing about what it stores. A name like itemCount tells you exactly what the number represents.
The extra few keystrokes always pay off when you or someone else reads the code later.
Using Variables with Different Data Types
A variable can hold any type of value in JavaScript. The language is dynamically typed, which means a single variable can hold a string at one moment and a number at the next.
let value = "hello";
console.log(typeof value);
value = 42;
console.log(typeof value);
value = true;
console.log(typeof value);The typeof operator tells you what kind of value is currently stored. This example prints string, then number, then boolean. The same variable changed types three times without any errors.
In practice, most variables keep the same type throughout their lifetime. Changing types on a single variable makes code harder to follow, so avoid it unless you have a specific reason. Here are common data types you will store in variables:
let productName = "Wireless Mouse";
let unitPrice = 29.99;
let inStock = true;
let tags = ["electronics", "sale"];
let customer = { name: "Alex" };
let discount = null;Each variable holds one kind of data, and the name hints at what type to expect. Strings store text, numbers store quantities and prices, booleans store true or false flags, arrays store ordered lists, and objects store structured data with named properties. For a complete exploration of every data type, see the JavaScript data types guide.
Common Beginner Mistakes
Beginners often forget to use a declaration keyword before a variable name. If you assign a value without let or const, JavaScript either creates an accidental global variable or throws an error in strict mode:
// Wrong: no declaration keyword
points = 10;Always start every variable with let or const. Modern JavaScript modules enable strict mode by default, which catches undeclared assignments as errors rather than silently creating global variables that pollute your entire application.
Another common mistake is confusing variable names with strings. Variable names are not wrapped in quotes. Writing "score" gives you a literal string, not the variable value:
let score = 100;
console.log(score); // 100, the variable
console.log("score"); // "score", just a stringThe first log accesses the variable and prints 100. The second log prints the literal text "score" because the quotes tell JavaScript to treat it as a string, not as a variable name.
Finally, beginners sometimes try to redeclare the same variable name with let twice in the same scope. This throws a SyntaxError and the code will not run at all:
let count = 1;
// let count = 2; // SyntaxError: already declared
count = 2; // Correct: reassign without letIf you need to update the value, just reassign it without the declaration keyword. The keyword only appears once, when the variable is first created.
Putting Variables to Work
Here is a realistic example that uses variables to calculate a discounted price. Each variable holds one piece of the calculation, and the names make the math self-explanatory:
const originalPrice = 50;
const discountPercent = 20;
const discountAmount = originalPrice * (discountPercent / 100);
const finalPrice = originalPrice - discountAmount;
console.log("Original:", originalPrice);
console.log("You save:", discountAmount);
console.log("Final price:", finalPrice);This prints Original: 50, You save: 10, and Final price: 40. The constants originalPrice and discountPercent never change. The derived values discountAmount and finalPrice are computed once and also never change, so const is the right choice for all four variables.
If the discount changes next week, you only update one number. The rest of the calculation adapts automatically because every value flows from the variables defined at the top. This pattern of defining inputs as constants and computing outputs from them appears in nearly every real JavaScript program.
To continue learning about variables, read the var vs let vs const comparison to understand all three declaration keywords, or work through the step-by-step guide on declaring and using variables.
Rune AI
Key Insights
- A variable is a named container that holds a value in memory.
- Declare variables with let or const, not var.
- let allows reassignment; const does not.
- Use descriptive names that explain what the value represents.
- Variables can store any data type: strings, numbers, booleans, arrays, objects, and more.
Frequently Asked Questions
What is a variable in JavaScript?
What is the difference between let and const?
Can I use a variable before declaring it?
Conclusion
Variables give your data a name so you can use it anywhere in your code. Declare them with let when the value changes and const when it should not. Every JavaScript program uses variables to store, track, and pass around information.
More in this topic
Is JavaScript Frontend or Backend? Full Guide
JavaScript is both a frontend and backend language. Learn the difference between browser JavaScript and Node.js, what each is used for, and which one you should learn first.
Learn JavaScript Step by Step Tutorial with Real Examples
Follow a hands-on tutorial that teaches JavaScript by building a real interactive page. Write your first variables, functions, and event listeners with examples you can run.
JavaScript Tutorial: Complete Beginner's Guide to Programming in 2025
A structured learning path for absolute beginners. Learn what to study first, how to practice, and which JavaScript concepts matter most when you are starting from zero.