EasyCode365EasyCode365

Variables in JavaScript

A variable is a named box where you can store a value so you can use it later.

How to create a variable

Use const when the value should not change, and let when the value needs to change later.

Can edit
const name = "Alex";
let age = 30;
console.log(age);

Example explained

Let's read the code line by line:

  • const name = "Alex"; creates a variable named name and stores the text "Alex" inside it. We use const because this name is not meant to change in this example.
  • let age = 30; creates a variable named age and stores the number 30 inside it. We use let because age is a value that could change later.
  • console.log(age); prints the current value of age in the output section below the code.

Why it matters

Variables let you reuse values without typing them over and over. You can also update them as your program runs.

Mini Task

Edit the code block above and try this:

  1. Change 30 to another age.
  2. Click Run.
  3. Check how the output changes below the code.

Short Quiz

Question 1: Which keyword should you usually use when a value should not change? A) const B) let C) console.log

Question 2: Which keyword should you use when a value needs to change later? A) const B) let C) string

(Answers: 1 - A, 2 - B)

Challenge

Now try updating a variable more than once. Click Run and watch the final output.

Can edit
let score = 0;
score = score + 1;
score = score + 1;
score = score + 1;

console.log(score);

Summary

  • A variable stores a value under a name.
  • Use const by default.
  • Use let when the value needs to change later.
  • console.log() lets you check a variable's current value in the output section.