javascript

Variable Declaration

Learn how to declare variables in JavaScript using `let`, `const`, and `var`. Understand the rules for naming, assigning values, and when to use each keyword for clear, correct code.

10 min read 8 sections Tutorial
Share

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

Getting Started

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.

javascript
1// Declare a variable named 'score' and give it an initial value of 0
2let score = 0;
3
4// Declare a variable named 'playerName' and set its value to 'Hero'
5const playerName = 'Hero';
6
7// Declare a variable named 'level' without an initial value
8let level;
9
10// Now, assign a value to 'level'
11level = 1;
12
13// Print the values to see what's inside
14console.log(score); // Outputs: 0
15console.log(playerName); // Outputs: Hero
16console.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.

javascript
1// Declare 'lives' with 'let' and initialize it to 3
2let lives = 3;
3console.log('Starting lives:', lives); // Outputs: Starting lives: 3
4
5// 'lives' can be changed because it was declared with 'let'
6lives = lives - 1; // Player loses a life
7console.log('Lives left:', lives); // Outputs: Lives left: 2
8
9// Declare 'GAME_TITLE' with 'const' and initialize it
10const GAME_TITLE = 'Space Invaders';
11console.log('Game Title:', GAME_TITLE); // Outputs: Game Title: Space Invaders
12
13// Trying to change a 'const' variable will cause an error
14// GAME_TITLE = 'New Title'; // ❌ TypeError: Assignment to constant variable.
✗ BadWrong — No Keyword
playerScore = 10; // This creates a global variable (bad!)
console.log(playerScore);
✓ GoodCorrect — Use let/const
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.

Use let for changeable values
// A counter that increases
let count = 0;
count = count + 1;
console.log(count); // 1
// User input that might change
let username = 'guest';
username = 'Alice';
console.log(username); // Alice
VS
Use const for fixed values
// A mathematical constant
const PI = 3.14159;
console.log(PI); // 3.14159
// A game setting that doesn't change
const 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.

1

Declare fixed values with `const`

First, declare any values that will not change throughout your program. These are often settings or fixed numbers.

javascript
1const taxRate = 0.05; // 5% tax
2const currencySymbol = '$'; // US Dollar
2

Declare changeable values with `let`

Next, declare variables that will hold values that can change, like user input or calculated results.

javascript
1let itemPrice = 20; // Price of an item
2let quantity = 2; // Number of items bought
3

Perform calculations and update `let` variables

Use your declared variables to do work. The results of calculations can be stored in other let variables.

javascript
1let subtotal = itemPrice * quantity; // 20 * 2 = 40
2let totalTax = subtotal * taxRate; // 40 * 0.05 = 2
3let finalTotal = subtotal + totalTax; // 40 + 2 = 42
4

Display the results

Finally, use your variables to show information to the user or for further processing.

javascript
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

KeywordCan Reassign?Scope TypeWhen to Use
letYesBlock scope `{}`When the variable's value will change (e.g., counters, user input, loop variables).
constNo (value is fixed)Block scope `{}`When the variable's value should never change (e.g., constants, configuration settings, fixed data).
varYesFunction scopeAvoid in new code. Only use if you are working with very old JavaScript.

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which keyword should you use for a variable whose value you expect to change later in the program?

Quick Check

What happens if you declare a const variable without assigning it an initial value?

Quick Check

Which of the following is NOT a valid variable name declaration in JavaScript?

Quick Check

What is the main reason let and const are preferred over var in modern JavaScript?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Declaration — the process of creating a new variable, giving it a name.
  • 2Initialization — giving a variable its first value when you declare it.
  • 3let keyword — use for variables whose values will change or be reassigned.
  • 4const keyword — use for variables whose values should remain fixed and never change.
  • 5var keyword — an older keyword; avoid using it in new JavaScript code.
  • 6Prefer const — start by using const for all variables, and only switch to let if 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 Scopelet and const variables are only accessible within the {} block where they are declared.
  • 10Always Declare — never use a variable without declaring it first with let or const to 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.

Continue Learning