Variable declaration is how you tell JavaScript that you want to create a named storage space for a value. You give this space a name and prepare it to hold information. This tutorial will teach you how to declare variables using `let`, `const`, and `var`, and explain when to use each one.
Variable Declaration
Variable Declaration
In JavaScript, variable declaration is the process of creating a new variable. It's like telling the computer, "Hey, I'm going to need a box to store something, and I'm going to call this box 'myNumber'." You declare a variable before you can put any value inside it.
JavaScript offers three main keywords to declare variables: let, const, and var. Each keyword has slightly different rules about how the variable behaves after it's declared.
What is Variable Declaration?
Variable declaration is the act of defining a new variable in your code. It reserves a name for a storage location, preparing it to hold a value.
let
Declares a variable whose value can be changed later. This is often the best choice for variables that need to update.
const
Declares a constant variable whose value cannot be changed after it's set. Use this for fixed values.
var
The older way to declare variables. It has some confusing behaviors, so let and const are preferred for new code.
Naming Rules
Variable names must follow specific rules: they cannot start with a number and cannot contain spaces or special symbols.
How to Declare a Variable
How to Declare a Variable
To declare a variable, you simply use one of the keywords (let, const, or var) followed by the name you want to give your variable. You can also give it a value right away, which is called initialization.
When you initialize a variable, you are not only declaring it but also putting the first value into its box. If you declare it without a value, it will automatically get a special value called undefined.
1// Declare a variable named 'score' and give it an initial value of 02let score = 0;34// Declare a variable named 'playerName' and set its value to 'Hero'5const playerName = 'Hero';67// Declare a variable named 'level' without an initial value8let level;910// Now, assign a value to 'level'11level = 1;1213// Print the values to see what's inside14console.log(score); // Outputs: 015console.log(playerName); // Outputs: Hero16console.log(level); // Outputs: 1
Always Declare Variables First
It is a common mistake to try and use a variable before you declare it. JavaScript will not know what you are talking about and will give you an error.
console.log(gameName); // ❌ ReferenceError: gameName is not defined
let gameName = 'Adventure Quest';
Always declare your variable with let or const before you try to read or change its value.
What Happens When You Declare?
What Happens When You Declare?
When you declare a variable, JavaScript creates a special space in the computer's memory. It labels this space with the name you chose for your variable. This is like putting a sticky note with a name on an empty box.
When you assign a value, JavaScript puts that value into the named memory space. From then on, whenever you use the variable's name, JavaScript looks up that memory space and uses whatever value is stored there. This is how your programs remember information.
1// Declare 'lives' with 'let' and initialize it to 32let lives = 3;3console.log('Starting lives:', lives); // Outputs: Starting lives: 345// 'lives' can be changed because it was declared with 'let'6lives = lives - 1; // Player loses a life7console.log('Lives left:', lives); // Outputs: Lives left: 289// Declare 'GAME_TITLE' with 'const' and initialize it10const GAME_TITLE = 'Space Invaders';11console.log('Game Title:', GAME_TITLE); // Outputs: Game Title: Space Invaders1213// Trying to change a 'const' variable will cause an error14// GAME_TITLE = 'New Title'; // ❌ TypeError: Assignment to constant variable.
playerScore = 10; // This creates a global variable (bad!)console.log(playerScore);
let playerScore = 10; // Declare with 'let'console.log(playerScore); // Outputs: 10// Or for a fixed value:const HIGH_SCORE = 1000;console.log(HIGH_SCORE); // Outputs: 1000
Choosing Your Declaration Keyword
Choosing Your Declaration Keyword
JavaScript gives you let, const, and var for declaration. Each one has a specific purpose. Knowing which one to use is important for writing clean and bug-free code.
Modern JavaScript mostly uses let and const. The var keyword is an older way to declare variables and is rarely used in new projects because it can lead to confusing behavior.
// A counter that increaseslet count = 0;count = count + 1;console.log(count); // 1// User input that might changelet username = 'guest';username = 'Alice';console.log(username); // Alice
// A mathematical constantconst PI = 3.14159;console.log(PI); // 3.14159// A game setting that doesn't changeconst MAX_LIVES = 3;console.log(MAX_LIVES); // 3
// A counter that increaseslet count = 0;count = count + 1;console.log(count); // 1// User input that might changelet username = 'guest';username = 'Alice';console.log(username); // Alice
// A mathematical constantconst PI = 3.14159;console.log(PI); // 3.14159// A game setting that doesn't changeconst MAX_LIVES = 3;console.log(MAX_LIVES); // 3
Rule of Thumb: Prefer const
A good habit is to start by declaring all your variables with const. If you later find out that the variable's value needs to change, then you can switch it to let. This helps prevent accidental changes to values that should stay fixed.
Practical Variable Declaration
Practical Variable Declaration
In real-world JavaScript projects, you declare variables constantly. They are used to store everything: user names, scores, prices, settings, and more. Thinking about what kind of value you are storing helps you pick the right keyword.
For example, if you are building a simple calculator, you would declare variables for the numbers, the operation, and the final result. Each variable has a clear job.
Declare fixed values with `const`
First, declare any values that will not change throughout your program. These are often settings or fixed numbers.
1const taxRate = 0.05; // 5% tax2const currencySymbol = '$'; // US Dollar
Declare changeable values with `let`
Next, declare variables that will hold values that can change, like user input or calculated results.
1let itemPrice = 20; // Price of an item2let quantity = 2; // Number of items bought
Perform calculations and update `let` variables
Use your declared variables to do work. The results of calculations can be stored in other let variables.
1let subtotal = itemPrice * quantity; // 20 * 2 = 402let totalTax = subtotal * taxRate; // 40 * 0.05 = 23let finalTotal = subtotal + totalTax; // 40 + 2 = 42
Display the results
Finally, use your variables to show information to the user or for further processing.
1console.log('Subtotal: ' + currencySymbol + subtotal);2console.log('Tax: ' + currencySymbol + totalTax);3console.log('Total: ' + currencySymbol + finalTotal);
Avoid using 'var' in modern JavaScript
The var keyword has a confusing behavior called hoisting and function scope, which can lead to unexpected bugs. Unlike let and const which are block-scoped (meaning they only exist within the curly braces {} where they are declared), var can 'leak' out of blocks. Always use let or const instead.
Declaration Keyword Reference
Declaration Keyword Reference
| Keyword | Can Reassign? | Scope Type | When to Use |
|---|---|---|---|
| let | Yes | Block scope `{}` | When the variable's value will change (e.g., counters, user input, loop variables). |
| const | No (value is fixed) | Block scope `{}` | When the variable's value should never change (e.g., constants, configuration settings, fixed data). |
| var | Yes | Function scope | Avoid in new code. Only use if you are working with very old JavaScript. |
Test Your Knowledge
Test Your Knowledge
Which keyword should you use for a variable whose value you expect to change later in the program?
What happens if you declare a const variable without assigning it an initial value?
Which of the following is NOT a valid variable name declaration in JavaScript?
What is the main reason let and const are preferred over var in modern JavaScript?
Quick Reference
Quick Reference
- 1Declaration — the process of creating a new variable, giving it a name.
- 2Initialization — giving a variable its first value when you declare it.
- 3
letkeyword — use for variables whose values will change or be reassigned. - 4
constkeyword — use for variables whose values should remain fixed and never change. - 5
varkeyword — an older keyword; avoid using it in new JavaScript code. - 6Prefer
const— start by usingconstfor all variables, and only switch toletif reassignment is truly needed. - 7Naming Rules — variable names cannot start with a number, contain spaces, or special characters (except
_and$). - 8Camel Case — commonly used for variable names, e.g.,
myVariableName. - 9Block Scope —
letandconstvariables are only accessible within the{}block where they are declared. - 10Always Declare — never use a variable without declaring it first with
letorconstto prevent errors and dangerous global variables.
Data Types
Explore the different kinds of values variables can hold, such as numbers, strings, and booleans.
Variable Scope
Dive deeper into how block scope and function scope affect where your variables are accessible.
Operators
Learn how to perform calculations and comparisons using variables and JavaScript operators.
Functions
Understand how to pass variables into functions and return values from them.
You've Mastered Variable Declaration!
You now understand how to declare variables using let, const, and var, when to choose each keyword, and the important rules for naming. This foundational skill is essential for writing any JavaScript program.
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.