From Zero to Senior · The LabالعربيةGitHub

Chapter 8

Values, Variables and Decisions

8 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • recognise the basic kinds of values JavaScript works with
  • store values in variables with let and const
  • calculate and compare with operators
  • make a program choose what to do with if, else and switch
  • build a small ticket kiosk that decides a price by itself

Examples

8.1 Values: the raw material of a program

Create a file called values.js and type this program:

values.js⤓ File
console.log(42);
console.log(3.5);
console.log("Hello");
console.log(true);

console.log(typeof 42);
console.log(typeof "Hello");
console.log(typeof true);
Recorded output$ node values.js
42
3.5
Hello
true
number
string
boolean

8.2 Variables: giving a value a name

JavaScript gives you two words for creating a variable: let and const.

variables.js⤓ File
let score = 0;
console.log(score);

score = score + 10;
console.log(score);

const name = "Sara";
console.log("Player:", name);
Recorded output$ node variables.js
0
10
Player: Sara

Use let for a value that will change, such as a score, a counter or a total. Use const for a value that will not change once it is set, such as a player's name or the maximum number of players. If you try to change a const, JavaScript stops your program with an error:

const-error.js⤓ File
const maxPlayers = 4;
maxPlayers = 5;
Recorded output$ node const-error.js
const-error.js:2
maxPlayers = 5;
           ^

TypeError: Assignment to constant variable.
    at Object.<anonymous> (const-error.js:2:12)
    at Module._compile (node:internal/modules/cjs/loader:1781:14)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

8.3 Operators: calculating and comparing

An operator is a symbol that takes values and produces a new value. You already know most of the arithmetic operators from school.

operators.js⤓ File
const price = 12;
const count = 3;

console.log(price * count);
console.log(10 / 4);
console.log(10 % 4);

const first = "Sara";
const last = "Khan";
console.log(first + " " + last);
console.log(`Total: ${price * count} dollars`);

console.log(5 === 5);
console.log(5 === "5");
console.log(5 == "5");
Recorded output$ node operators.js
36
2.5
2
Sara Khan
Total: 36 dollars
true
false
true

8.4 Decisions with if and else

Now that you can compare values, you can make your program choose. The if statement runs a block of code only when a condition is true. A cinema charges different prices for different ages; here is how a program decides:

ticket.js⤓ File
const age = 9;
let price;

if (age < 4) {
  price = 0;
} else if (age < 13) {
  price = 6;
} else if (age >= 65) {
  price = 7;
} else {
  price = 10;
}

console.log(`Age ${age}: $${price}`);
Recorded output$ node ticket.js
Age 9: $6

8.5 Combining conditions

Real decisions often depend on more than one thing. Three logical operators let you combine booleans:

logic.js⤓ File
const isMember = true;
const day = "Tuesday";

if (isMember && day === "Tuesday") {
  console.log("Half price today!");
}

const hasTicket = false;
if (!hasTicket) {
  console.log("Please buy a ticket.");
}

const nickname = "";
const shown = nickname || "Guest";
console.log(shown);
Recorded output$ node logic.js
Half price today!
Please buy a ticket.
Guest

8.6 Choosing between many fixed values with switch

When you compare one value against a list of exact possibilities, a switch statement can be easier to read than a long chain of else if:

switch.js⤓ File
const size = "M";
let drink;

switch (size) {
  case "S":
    drink = 2;
    break;
  case "M":
    drink = 3;
    break;
  case "L":
    drink = 4;
    break;
  default:
    drink = 0;
}

console.log(`Drink: $${drink}`);
Recorded output$ node switch.js
Drink: $3

8.7 Project: a ticket kiosk

This is your first program that makes real decisions on its own. Read it once, run it, then change the values and play!

kiosk.js⤓ File
// Ticket kiosk: change these values and run again.
const age = 34;
const isMember = true;
const day = "Tuesday";
const showTime = 22; // 24-hour clock

let price;
if (age < 4) {
  price = 0;
} else if (age < 13 || age >= 65) {
  price = 6;
} else {
  price = 10;
}

if (isMember && day === "Tuesday") {
  price = price / 2;
}

if (showTime >= 22 && price > 0) {
  price = price - 1;
}

const message = price === 0 ? "Free entry" : `Please pay $${price}`;
console.log(message);
Recorded output$ node kiosk.js
Please pay $4

Practice projects

Project 8.1 · Easy

Exam grade calculator

Turn a score from 0 to 100 into a letter grade, say whether the student passed, and refuse impossible scores.

You will practise: if/else if chains, the order of conditions, || and &&, and the conditional operator.

Steps
  1. Write the grading table first: A from 90, B from 80, C from 70, D from 50, F below 50.
  2. Start the chain with the impossible cases: a score below 0 or above 100 is invalid. Why must this check come first?
  3. Continue the chain from the highest grade down. Each condition only needs the lower limit, because the earlier ones have already caught the higher scores.
  4. Calculate passed with &&, and print a message with the conditional operator.
  5. Test with 100, 90, 89, 50, 49, 0, -5 and 120. These are called boundary values: bugs love to hide there.

Hint: if you put score >= 50 before score >= 90, every passing student gets a D. The first true condition wins.

Solution
grade.js⤓ File
const score = 83;
let grade;

if (score < 0 || score > 100) {
  grade = "Invalid score";
} else if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else if (score >= 70) {
  grade = "C";
} else if (score >= 50) {
  grade = "D";
} else {
  grade = "F";
}

const passed = score >= 50 && score <= 100;
console.log(`Score ${score}: grade ${grade}`);
console.log(passed ? "Passed. Well done!" : "Not passed. Try again!");
Recorded output$ node grade.js
Score 83: grade B
Passed. Well done!

Project 8.2 · Medium

Delivery cost calculator

An online shop charges for delivery by weight, doubles the price for express delivery, adds a fee outside the big cities, and delivers free on large orders that are not express.

You will practise: several decisions in a row, !==, combining conditions, and rounding up with Math.ceil.

Steps
  1. Write the rules as a numbered list in plain language before any code: up to 1 kg costs 30; up to 5 kg costs 50; above 5 kg, 50 plus 10 for every extra kilogram started.
  2. Calculate the base cost from the weight. For the extra kilograms, Math.ceil(weight - 5) rounds up, so 6.2 kg counts as 2 extra kilograms.
  3. Apply express (× 2), then the fee for cities other than Cairo and Alexandria: the city is not Cairo and not Alexandria.
  4. Free delivery needs two things at once: an order total of 1000 or more, and not express (!express).
  5. Try at least five combinations and check each one by hand.

Hint: a classic mistake is city !== "Cairo" || city !== "Alexandria", which is always true. Say the rule out loud: “not Cairo and not Alexandria”.

Solution
shipping.js⤓ File
const weight = 3.5; // kg
const express = true;
const city = "Alexandria";
const orderTotal = 640;

let cost;
if (weight <= 1) {
  cost = 30;
} else if (weight <= 5) {
  cost = 50;
} else {
  cost = 50 + Math.ceil(weight - 5) * 10;
}

if (express) {
  cost = cost * 2;
}

if (city !== "Cairo" && city !== "Alexandria") {
  cost = cost + 20;
}

const free = orderTotal >= 1000 && !express;
console.log(`Weight: ${weight} kg, express: ${express}, city: ${city}`);
console.log(free ? "Shipping: free!" : `Shipping: ${cost}`);
Recorded output$ node shipping.js
Weight: 3.5 kg, express: true, city: Alexandria
Shipping: 100

Project 8.3 · Challenge

How many days in this month?

Given a year and a month, work out how many days the month has, getting February right in leap years.

You will practise: a complex condition with brackets, %, and a switch where several cases share one answer.

Steps
  1. Learn the leap year rule: a year is a leap year if it divides by 4, except years that divide by 100, except years that divide by 400. So 2024 and 2000 are leap years; 1900 is not.
  2. Write it as one boolean: (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0. Test it with 2024, 2023, 1900 and 2000.
  3. Write a switch on the month. February uses the leap year result. April, June, September and November have 30 days: let their cases fall through to the same code, with no break between them.
  4. Every other month has 31 days: that is the default.
  5. Print both results, and try February 1900. Many real programs have got that one wrong!

Hint: stacking case 4:, case 6:, case 9: and case 11: on top of each other is the one place where leaving out break is exactly what you want.

Solution
calendar.js⤓ File
const year = 2028;
const month = 2;

// Leap years: every 4 years, except every 100, except every 400
const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;

let days;
switch (month) {
  case 2:
    days = isLeap ? 29 : 28;
    break;
  case 4:
  case 6:
  case 9:
  case 11:
    days = 30;
    break;
  default:
    days = 31;
}

console.log(`${year} is a leap year: ${isLeap}`);
console.log(`Month ${month} of ${year} has ${days} days`);
Recorded output$ node calendar.js
2028 is a leap year: true
Month 2 of 2028 has 29 days

Exercises

Exercise 8.1 · Easy

Write a program with a const called temperature. Print "Cold" below 15, "Warm" from 15 to 29, and "Hot" from 30 up.
The book's short answer
const temperature = 22;
if (temperature < 15) {
  console.log("Cold");
} else if (temperature < 30) {
  console.log("Warm");
} else {
  console.log("Hot");
}
Show the solution
check-all.js⤓ File
// The same rule tested at the edges (14, 15, 29, 30), where mistakes like < instead of <= hide.
// It uses a loop from Chapter 9 and a function from Chapter 10.
function describe(temperature) {
  if (temperature < 15) return "Cold";
  if (temperature < 30) return "Warm";
  return "Hot";
}

for (const t of [-3, 14, 15, 22, 29, 30, 41]) {
  console.log(`${t} -> ${describe(t)}`);
}
Recorded output$ node check-all.js
-3 -> Cold
14 -> Cold
15 -> Warm
22 -> Warm
29 -> Warm
30 -> Hot
41 -> Hot
temperature.js⤓ File
// Change the temperature and run the program again.
const temperature = 22;

if (temperature < 15) {
  console.log("Cold");
} else if (temperature < 30) {
  console.log("Warm");
} else {
  console.log("Hot");
}
Recorded output$ node temperature.js
Warm

Exercise 8.2 · Easy

Predict the output of each line, then check with Node: 7 % 3, "7" + 3, 7 === "7", !true.
The book's short answer
1, "73", false, false.
Show the solution
predict.js⤓ File
console.log(7 % 3); // 1: the remainder of 7 ÷ 3
console.log("7" + 3); // "73": one side is text, so + joins
console.log(7 === "7"); // false: === also compares the type, number against text
console.log(!true); // false: ! turns true into false

// typeof shows why the second line joined instead of adding:
console.log(typeof ("7" + 3));
Recorded output$ node predict.js
1
73
false
false
string

Exercise 8.3 · Medium

A number is even when n % 2 === 0. Print whether a number is even or odd, and whether it is positive, negative or zero.
The book's short answer
Check n % 2 === 0 for even, then n > 0, n < 0, or zero in a second if.
Show the solution
even-odd.js⤓ File
// Change n and run again: try 8, -7 and 0.
const n = -7;

// Question 1: even or odd? (-7 % 2 is -1, which is not 0, so -7 is odd.)
if (n % 2 === 0) {
  console.log(`${n} is even`);
} else {
  console.log(`${n} is odd`);
}

// Question 2: a separate if, because it is a separate question.
if (n > 0) {
  console.log("positive");
} else if (n < 0) {
  console.log("negative");
} else {
  console.log("zero");
}
Recorded output$ node even-odd.js
-7 is odd
negative

Exercise 8.4 · Medium

Rewrite switch.js using if and else if. Which version do you find easier to read, and why?
The book's short answer
Each case becomes if (size === "S"), else if (size === "M") and so on. Most people find switch clearer for exact values and if clearer for ranges.
Show the solution
switch-as-if.js⤓ File
// switch.js rewritten with if and else if.
const size = "M";
let drink;

if (size === "S") {
  drink = 2;
} else if (size === "M") {
  drink = 3;
} else if (size === "L") {
  drink = 4;
} else {
  drink = 0;
}

console.log(`Drink: $${drink}`);

// Which is easier to read? For exact values like "S", "M" and "L", switch lists them neatly and says
// "one value, many cases". For ranges (age < 13), only if works, because case compares with ===.
Recorded output$ node switch-as-if.js
Drink: $3

Exercise 8.5 · Challenge

Add a fifth rule to the kiosk: on Fridays everyone pays 2 extra, but the price can never be more than 10. Test at least four different visitors.
The book's short answer
After the other rules: if (day === "Friday") { price = price + 2; } if (price > 10) { price = 10; }
Show the solution
kiosk.js⤓ File
// The ticket kiosk with a fifth rule: Fridays cost 2 extra, but never more than 10 in total.
// Change these values and run again.
const age = 34;
const isMember = false;
const day = "Friday";
const showTime = 20; // 24-hour clock

let price;
if (age < 4) {
  price = 0;
} else if (age < 13 || age >= 65) {
  price = 6;
} else {
  price = 10;
}

if (isMember && day === "Tuesday") {
  price = price / 2;
}

if (showTime >= 22 && price > 0) {
  price = price - 1;
}

// The new rule comes last, so the limit applies to the final price.
if (day === "Friday") {
  price = price + 2;
}
if (price > 10) {
  price = 10;
}

const message = price === 0 ? "Free entry" : `Please pay $${price}`;
console.log(message);
Recorded output$ node kiosk.js
Please pay $10
test-visitors.js⤓ File
// Four (and more) visitors at once. The rules are the same as kiosk.js, inside a function (Chapter 10).
function kiosk(age, isMember, day, showTime) {
  let price;
  if (age < 4) {
    price = 0;
  } else if (age < 13 || age >= 65) {
    price = 6;
  } else {
    price = 10;
  }
  if (isMember && day === "Tuesday") price = price / 2;
  if (showTime >= 22 && price > 0) price = price - 1;
  if (day === "Friday") price = price + 2;
  if (price > 10) price = 10;
  return price;
}

const tests = [
  // age, member, day, time, expected
  [34, false, "Friday", 20, 10], // 10 + 2 = 12, capped at 10
  [9, false, "Friday", 20, 8], // 6 + 2
  [2, false, "Friday", 20, 2], // a free baby pays 2 on Fridays: is that what we want? Decide and say so.
  [70, false, "Friday", 23, 7], // 6 - 1 + 2
  [34, true, "Tuesday", 20, 5], // not Friday: unchanged
];

for (const [age, member, day, time, expected] of tests) {
  const price = kiosk(age, member, day, time);
  const ok = price === expected ? "✓" : "✗";
  console.log(`${ok} age ${age}, ${day} ${time}:00 -> ${price}`);
}
Recorded output$ node test-visitors.js
✓ age 34, Friday 20:00 -> 10
✓ age 9, Friday 20:00 -> 8
✓ age 2, Friday 20:00 -> 2
✓ age 70, Friday 23:00 -> 7
✓ age 34, Tuesday 20:00 -> 5