Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Understanding Variables in JavaScript | Variables and Data Types in JavaScript
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Introduction to JavaScript

bookUnderstanding Variables in JavaScript

Swipe to show menu

Variables let you store and reuse values in your programs.

Note
Note

A variable is like a container that can hold numbers, text, or more complex data.

Defining Variables

Use the let keyword to create a variable:

let variableName;
Note
Note

Variable names should follow camelCase (first word lowercase, next words capitalized).

A newly created variable has the value undefined, meaning no value has been assigned yet.

You can assign a value later:

let x;
x = 5;

Or assign it immediately:

let x = 13;

Using Variables

Variables help avoid repeating the same value in your code:

1234
let word = "VariableText"; // The variable value is the `"VariableText"` console.log("ValueText"); // Print the `"ValueText"` console.log(word); // Print the variable value
copy

You can reassign values anytime:

123456
let numb; numb = 100; console.log(numb); numb = 100 + 20; console.log(numb);
copy

Why Variables Matter

Without variables, you would have to rewrite the same value many times and fix every occurrence if there's a typo.

Example with repeated text:

1234
console.log("Hello Word!"); console.log("I love this Word!"); console.log("I need to live in this Word!"); console.log("This Word is the best!");
copy

Using a variable makes fixes easier:

123456
let x = "Word"; console.log("Hello " + x + "!"); console.log("I love this " + x + "!"); console.log("I need to live in this " + x + "!"); console.log("This " + x + " is the best!");
copy

Change "Word" to "World" once, and all lines update.

Note
Note

This uses string concatenation, which youโ€™ll learn next.

Note

In the example above, we used string concatenation. We will delve into string concatenation in the next section.

question-icon

Define a variable:

let = ;

Click or drag`n`drop items and fill in the blanks

Everything was clear?

How can we improve it?

Thanks for your feedback!

Sectionย 2. Chapterย 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Sectionย 2. Chapterย 1
some-alt