JavaScript - 2

JavaScript - 2: Variables

Variables let you store values so you can reuse them later in your program.

In this lesson, you will store a name as text and an age as a number, then combine both values inside a message.

Your challenge: Create two variables called name and age, then print a sentence using both.

✦ JavaScript Editor
▶ Live Output

What is a variable?

A variable is a named place where JavaScript can store a value.

For example: let name = "Riley";

The variable is called name, and the value stored inside it is the string "Riley".

You can use the variable later instead of typing the value again.

Strings and numbers

A name is text, so it needs quotation marks: let name = "Riley";

An age is a number, so it does not need quotation marks: let age = 24;

This difference matters because JavaScript treats text and numbers as different types of values.

Using the variables

You can print a variable directly: console.log(name);

JavaScript looks inside the variable and prints its current value.

You can also combine text and variables using the + operator: console.log("Hello, " + name);

When + is used with strings, it joins pieces of text together. This is called string concatenation.

Build the full sentence:

Try joining text, name, and age into one message.

For example, if: name contains "Riley" and age contains 24, the output should read: Hi, I'm Riley and I am 24 years old.

Experiment: Change only the value stored in name.

You should not need to rewrite the console.log() statement. The message updates because it reads the value from the variable.

Then change the age and run the code again.

Variables can change:

A variable created with let can be given a new value later.

For example: let score = 5;

Then later: score = 10;

Notice that the second line does not use let again. The variable already exists, so the new value is simply assigned to it.

Variable names matter:

Names such as name, age, and score make the purpose of a value easier to understand.

A name such as x can work, but it may be less clear when the program becomes larger.

One more experiment:

Create a third variable called hobby and include it in another message.

For example: I enjoy drawing.

Good JavaScript habit: Give variables clear names that describe what they contain. That makes your code easier to read and easier to change later.

👀 Show Solution
let name = "Riley";
let age = 24;

console.log("Hi, I'm " + name + " and I am " + age + " years old.");

The first variable stores a string, while the second stores a number. The console.log() statement joins both values with the surrounding text to create one complete sentence.