B4Coder
0%
LessonAbout 5 min

Chapter 1 · Lesson 3 of 5

03. Keeping values in variables

Give a value a name with let or const, use it again and again, and change it when you need to.

A variable is a name for a value, so you can use it again. Make one with let, a name, = and the value. Later, give it a new value with just the name and =.

JavaScript
let score = 10;console.log("Score:", score);score = score + 5;console.log("Score:", score);

It shows

Score: 10
Score: 15

Use const for a value that never changes. JavaScript stops you if you try to change it, which catches mistakes early.

Names can't have spaces, so join words with capitals: totalMarks, firstName. That's called camelCase.

JavaScript
const pricePerKg = 40;let kgs = 3;console.log("Pay:", pricePerKg * kgs);kgs = 5;console.log("Pay:", pricePerKg * kgs);

It shows

Pay: 120
Pay: 200

Your turn

1Steps

  1. 1Make a const called ticket for a cinema ticket that costs 150, and a let called friends set to 3.
  2. 2Show Cost: and ticket * friends. Then change friends to 5 and show Cost: again.

Write it in script.js. If it asks with prompt(), put the answers in Program input, under the terminal.

Use: const, let, console.log

Starting code

The editor starts empty. Copy this into it to begin, or write your own from scratch.

JavaScript
console.log("Cost:", 150 * 3);console.log("Cost:", 150 * 5);

2Expected output

It should show

Cost: 450
Cost: 750

3Hints

Stuck? Open one hint at a time: each gives a bit more help.

Hint 1

Start with const ticket = 150; and let friends = 3;

Hint 2

Show it with console.log("Cost:", ticket * friends);

Hint 3

Then friends = 5; (no let this time) and the same console.log again.

JavaScript ready

Terminal

Click Run to see what your program shows, then Submit answer to check it and unlock Next.