JavaScript from zero: values, decisions and loops
Lesson 5 of 8
5JavaScript from zero: values, decisions and loops
The big pictureHTML is structure and CSS is looks, but neither one "thinks". JavaScript is the only language every browser in the world understands, and with it the page calculates, decides and responds. With Node.js it runs on servers too. Here you learn the language itself step by step before touching the page.
What the picture shows: The ingredients of any program: a value you store in a variable, a decision that picks a path, a loop that repeats a step, and an output you print to see it.
Map of this part
The concepts in order, click any one to jump to it:
Two ways into the same idea
JavaScript is the page's "muscles": HTML is the skeleton, CSS the clothes, JavaScript the movement. A program is like a recipe: ingredients you put in labelled bowls (variables), steps in order, "if the milk is too hot, wait a minute" (a decision), and "stir ten times" (a loop). The computer is a very fast cook but a very literal one: it does exactly what you wrote, not what you meant.
An interpreted, dynamically typed language, compiled at run time by a JIT engine (V8 in Chrome and Node). Seven primitive types (string, number, boolean, null, undefined, bigint, symbol); everything else is an object. let/const are block-scoped with a temporal dead zone (TDZ), while var is function-scoped and hoisted, so avoid it. number is a double-precision float (IEEE 754), which is why 0.1 + 0.2 !== 0.3. == coerces types by confusing rules and === does not. There are six "falsy" values: false, 0, "", null, undefined, NaN; everything else is "truthy" in a condition. Loops: the classic for, for...of for arrays and strings, and while, with break and continue.
Before You Start
🧩Programming logic
From stage 0: you know the idea of variables, decisions and loops without code.
📄Your first web page
You write an HTML file and open it in a browser.
🐍Python helps
If you studied Python you will spot the likeness at once; the differences are braces and semicolons.
The Core Idea
1Where do you write JavaScript and where do you see its output?
Three places: (1) right here in the lesson: press "Run" under any example, edit the code and run it again. (2) in the browser: press F12, open the Console tab, type a line and press Enter. (3) in your page: inside a <script> tag just before the end of body, or in an app.js file linked with <script src="app.js"></script>.
The command you will write thousands of times is console.log(...): it prints any value to the Console so you can see what is happening inside your program. A comment starts with // for one line, and the browser ignores it.
// my first program: press Run
console.log("Hello, Darb!");
console.log(2 + 3);
console.log("2" + "3"); // text joined to text, not maths
console.log(10 / 4, 10 % 4, 2 ** 10);"2" + "3" gave 23, not 5: the quotes make them text, and + between two texts glues them. It is the first of many surprises that teach you to watch the type of a value.2Variables: const and let
A variable is a name for a value you keep to use later. const is for a value you will not rebind to something else, which is most variables. let is for a value that will change, like a counter. Do not use the old var. Names are English, start lowercase and run words together with a capital for each new word: totalPrice (camelCase).
const shopName = "Darb Cafe";
const pricePerCup = 14;
let cups = 2;
console.log(shopName, "sells a cup for", pricePerCup);
cups = cups + 1; // let can change
cups += 1; // the same, shorter
console.log("cups now:", cups);
console.log("bill:", cups * pricePerCup);const. Write pricePerCup = 15 after declaring it with const and the program stops with "Assignment to constant variable". That is not a flaw but a guard: const tells you and your teammates "this value does not change".3Kinds of values: text, number and true/false
Every value has a type, and typeof tells you which. Text string goes in quotes. A number number has no quotes, whole or decimal. A boolean has only two values: true and false. undefined means "not given a value yet", and null means "no value, on purpose".
const name = "Sara";
const age = 21;
const isMember = true;
let nickname; // no value yet
console.log(typeof name, typeof age, typeof isMember, typeof nickname);
console.log(Number("42") + 1, String(42) + 1); // converting on purpose
console.log(Number("abc")); // NaN: "not a number"
console.log(0.1 + 0.2); // decimals are approximate!Look at the last line: 0.1 + 0.2 is not exactly 0.3, because the computer stores decimal fractions in binary approximately. That is why money is calculated in cents or halalas (whole numbers) and divided by 100 only for display.
4Working with text
The easiest way to build text from values is a template literal with backticks ` `: you write ${...}` inside it and put any value or expression there. Strings come with ready-made tools (methods) you call with a dot: length, upper case, trimming, searching, replacing.
const customer = " noura ";
const drink = "latte";
const cups = 3;
const clean = customer.trim();
console.log(`Hello ${clean}, ${cups} x ${drink} = ${cups * 14} SAR`);
console.log(drink.length, drink.toUpperCase(), drink[0]);
console.log(drink.includes("tt"), drink.replace("latte", "mocha"));
console.log("05-123-4567".split("-"));5Comparison and logic: ===, && and ||
A comparison gives true or false: >, <, >=, <=, and === "exactly equal" and !== "not equal". To join two conditions: && means "and" (both true), || means "or" (either is enough), and ! means "not".
const age = 17;
const hasTicket = true;
console.log(age >= 18); // false
console.log(age >= 18 && hasTicket); // both? false
console.log(age >= 18 || hasTicket); // either? true
console.log(!hasTicket); // not: false
console.log("5" === 5, "5" == 5); // strict vs loose
console.log("" == 0, null == undefined); // loose surprises== instead of ===. Loose equality converts types silently: "" == 0 and "0" == 0 are both true. These bugs show no message, just a wrong result that reaches the user. Always write ===.6Decisions: if and else
if (condition) { ... } runs the block only when the condition is true. else handles the other case, and else if covers several cases in order, stopping at the first true one. The ternary condition ? a : b is a short decision that gives a value.
function discountFor(total) {
if (total >= 100) {
return 0.15;
} else if (total >= 50) {
return 0.05;
} else {
return 0;
}
}
for (const total of [30, 60, 120]) {
const rate = discountFor(total);
const label = rate > 0 ? `${rate * 100}% off` : "no discount";
console.log(total, "->", label, "->", total - total * rate);
}Truthy and falsy: in a condition, any value turns into true or false. Only six values are "falsy": false, 0, "" (empty text), null, undefined and NaN. Everything else is truthy, even "0" and "false" as text. So if (name) means "if the name is not empty".
7Loops: for and while
A loop repeats steps instead of writing them many times. for (let i = 1; i <= 5; i++) counts from 1 to 5: a start, a keep-going condition, a step. for (const x of list) visits each item in a list, and is usually the clearest. while (condition) repeats as long as the condition holds. break leaves the loop, and continue skips to the next round.
// 1. count
for (let i = 1; i <= 3; i++) {
console.log("cup number", i);
}
// 2. visit every item
const orders = ["latte", "mocha", "v60"];
for (const drink of orders) {
if (drink === "mocha") continue; // skip mocha
console.log("making", drink);
}
// 3. repeat while a condition holds
let beans = 100;
let cupsMade = 0;
while (beans >= 18) {
beans -= 18;
cupsMade++;
}
console.log(cupsMade, "cups, beans left:", beans);while (beans > 0) where you forgot to reduce beans inside it. The tab freezes. Always make sure something inside the loop moves the condition closer to false.Worked example
Problem: a café bill calculator. We have the cups and price of each drink. Compute the total, apply a 10% discount if it exceeds 50 SAR, add 15% tax, and print the bill. Steps: loop over the orders adding cups × price to the total, then a decision for the discount, then the tax, then print with a template literal. We work in halalas to avoid 0.1 + 0.2 fractions:
const order = [
{ drink: "latte", cups: 2, price: 1400 }, // prices in halalas
{ drink: "mocha", cups: 1, price: 1600 },
{ drink: "v60", cups: 2, price: 1800 },
];
let subtotal = 0;
for (const line of order) {
const lineTotal = line.cups * line.price;
console.log(`${line.cups} x ${line.drink}`.padEnd(14), (lineTotal / 100).toFixed(2));
subtotal += lineTotal;
}
const discount = subtotal > 5000 ? Math.round(subtotal * 0.10) : 0;
const tax = Math.round((subtotal - discount) * 0.15);
const total = subtotal - discount + tax;
console.log("subtotal".padEnd(14), (subtotal / 100).toFixed(2));
console.log("discount".padEnd(14), (-discount / 100).toFixed(2));
console.log("VAT 15%".padEnd(14), (tax / 100).toFixed(2));
console.log("TOTAL".padEnd(14), (total / 100).toFixed(2), "SAR");Try it: change the mocha cups to 0 and run: does the discount still apply? Then add a line for a fourth drink.
Myth vs Reality
| Myth | Reality |
|---|---|
| JavaScript is Java. | Two entirely different languages; the shared name was 1995 marketing. |
| const means the value never changes. | It only prevents rebinding. The contents of a const object or array can change. |
| JavaScript is only for the browser. | With Node.js it runs on servers, and mobile and desktop apps are built with it too. |
Where you meet it at work
🧮Calculations in the page
A shop cart, a loan calculator, a character counter: all variables and decisions.
✅Checking input
"If the password is shorter than 8, show a warning" is an if.
🖥️Node.js servers
You write the server in the same language in the Express lesson.
Test your understanding
What is "5" === 5?
=== compares type too: a string and a number differ.
What is "4" + 4?
When either side is text, + glues instead of adding.
Which variable suits a counter that goes up each time?
let for what changes, const for what is not rebound.
Which value is "truthy" in a condition?
"0" is non-empty text, so it is truthy. Only six are falsy: false, 0, "", null, undefined, NaN.
How many times does for (let i = 0; i < 3; i++) console.log(i) print?
i takes 0, 1 and 2; at 3 the condition is false and it stops.
Quick review cards
Check Your Understanding
Why does 0.1 + 0.2 not equal 0.3?
Because decimal fractions are stored in binary approximately. For money, calculate in whole numbers (halalas or cents).
What is dangerous about ==?
It converts types implicitly, so comparisons like "" == 0 become true by accident.
What is the difference between undefined and null?
undefined: not given a value yet. null: no value, on purpose by the programmer.
How do you avoid an endless loop?
Make sure something inside the loop changes the variable the condition depends on until it becomes false.
Resources for this lesson
Grouped by type. Start with the official docs for precision, or an article or video for the explanation.
Done with this lesson?
Sign in to save your progress.