JavaScript from absolute zero · Chapter 3 of 14 · Languages · new chapter every Tuesday morning
By the end of this chapter: Write correct conditional logic and avoid the comparison mistakes the language invites.
The problem
Say you are a junior developer at a regional airline. You have been tasked with writing a small script for the check-in desk that calculates baggage fees. The rule is simple: if a suitcase weighs more than 20kg, the passenger must pay a £40 surcharge. If it is 20kg or less, it is free.
You write a script that takes the weight and prints the result. However, because you haven't yet mastered how to make the computer choose between two paths, your script prints "Surcharge applied" for every single passenger.
On a busy Saturday morning at Gatwick, 400 passengers check in. The staff, following the script's output, charge every person £40, including those with small carry-on bags. By 10:00 AM, the customer service desk is swamped with 150 angry travellers demanding refunds. The airline has to issue £6,000 in immediate refunds, and you are called into a meeting to explain why the "automated" system cannot tell the difference between a 5kg backpack and a 30kg trunk.
The cost wasn't just the money; it was the loss of trust from the ground staff who now refuse to use your software, reverting to pen and paper. To fix this, you need to move beyond code that runs in a straight line and learn how to make the computer branch.
Before you start
You must have Node.js installed on your computer, as covered in Chapter 1. You should be comfortable creating a new text file and running it from your terminal (the command-line interface).
To verify your setup, open your terminal and type:
node -v You should see a version number, such as v20.10.0 or v22.0.0. If you see an error saying "command not found", return to Chapter 1 to complete the installation.
How do we ask the computer a question?
In Chapter 2, we learned about types like Strings (text) and Numbers. To make decisions, we use a third type: the Boolean. A Boolean can only ever be one of two values: true or false.
We create Booleans by using comparison operators. These are symbols that compare two values and return a result.
Open your terminal, type node to enter the interactive mode, and try these comparisons:
25 > 20 // Output: true 15 > 20 // Output: false The > symbol means "greater than". Because 25 is larger than 20, the computer evaluates that expression (a piece of code that produces a value) as true.
Here are the primary comparison operators you will use:
-
>: Greater than -
<: Less than -
>=: Greater than or equal to -
<=: Less than or equal to -
===: Is exactly equal to -
!==: Is not equal to
Note the triple equals ===. In JavaScript, we use a single = to assign a value to a variable (e.g., let weight = 25). We use the triple equals === to ask if two things are the same. This is the most common source of bugs for beginners.
How do we branch the path?
To use these "true or false" answers, we use an if statement. An if statement tells the computer: "If this condition is true, run the code inside these curly braces. If it is not, skip it."
A condition is simply any expression that results in a Boolean (true or false).
The structure looks like this:
if (weight > 20) { console.log("Surcharge applied"); } If the weight is 25, the code inside the { } (called a block) runs. If the weight is 10, the computer ignores everything inside the braces and moves to the next line of the script.
To handle the "otherwise" scenario, we use the else keyword. This creates a second block of code that only runs if the first condition was false.
if (weight > 20) { console.log("Surcharge applied"); } else { console.log("No fee"); } This is a binary decision. One of these two blocks will run, but never both.
Why is === better than ==?
JavaScript is an old language that tries very hard to be helpful, often to its own detriment. It has two ways to check for equality: == (loose equality) and === (strict equality).
Loose equality (==) tries to convert the types of the values so they match before comparing them. This leads to "traps" that cause production crashes. For example:
// In your terminal: "40" == 40 // Output: true (The string "40" is converted to a number) false == 0 // Output: true (The boolean false is converted to the number 0) "" == 0 // Output: true (An empty string is converted to 0) This "helpfulness" is dangerous. If a user leaves a "Price" field empty, your code might treat that empty string as the number zero, potentially giving away products for free.
Strict equality (===) does not convert types. It checks if the values are the same and if the types are the same.
"40" === 40 // Output: false (A String is not a Number) In modern professional JavaScript, we almost never use ==. You should use === by default to ensure your logic is predictable.
What if there are more than two choices?
Real-world logic often requires more than just "Yes" or "No". At the airline, perhaps bags over 20kg cost £40, but bags over 30kg cost £100.
We handle this using else if. The computer checks these conditions in order, from top to bottom. As soon as it finds one that is true, it runs that block and ignores the rest.
let weight = 35; if (weight > 30) { console.log("Heavy surcharge: £100"); } else if (weight > 20) { console.log("Standard surcharge: £40"); } else { console.log("No fee"); } The order matters. If you checked weight > 20 first, a 35kg bag would trigger the £40 fee and the computer would stop looking, missing the £100 rule entirely. Always check your most specific or most restrictive condition first.
Build it
We will build a "Gate Access Controller". This script will check a user's age and whether they have a VIP pass to decide if they can enter a restricted area.
- Create a new file named
access.js. - Add the following code, which sets up our initial data:
let userAge = 17; let hasVipPass = true; - Now, add the logic. We want to allow entry if the user is 18 or older, OR if they have a VIP pass regardless of age. We use the
||symbol, which means OR. (The&&symbol means AND).
if (userAge >= 18 || hasVipPass === true) { console.log("Access Granted"); } else { console.log("Access Denied"); } - Save the file.
-
Run the script in your terminal:
node access.jsConfirm: You should see
Access Grantedbecause while the age is 17 (false), thehasVipPassistrue. In an OR statement, only one side needs to be true. Change
hasVipPasstofalsein your code and save. Run it again.
Confirm: You should seeAccess Deniedbecause both conditions are now false.Change
userAgeto21and save. Run it again.
Confirm: You should seeAccess Grantedbecause the age condition is now true.
When this breaks
Symptom: The code always runs the if block, even when it should be false.
The Cause: You likely used a single equals = instead of a triple equals ===.
if (hasVipPass = true) { // ERROR: This sets the variable to true, then evaluates it In JavaScript, assigning a value inside an if statement usually results in true.
The Fix: Always use === for comparisons.
Symptom: ReferenceError: weight is not defined
The Cause: You are trying to compare a variable that hasn't been created yet with let.
The Fix: Ensure your variables are declared at the top of the script before the if statement.
Symptom: Both the if and the else blocks seem to be skipped (or the wrong one runs).
The Cause: Check your "Truthiness". In JavaScript, the number 0, the value null, undefined, and an empty string "" are all considered falsy. If your variable contains any of these, if (variable) will behave as if it is false.
The Fix: Be explicit. Instead of if (score), use if (score > 0) or if (score !== 0).
What it costs
Conditional logic is the "brain" of your code, but it comes with a readability cost.
As you add more conditions, you might be tempted to put if statements inside other if statements (nesting). This creates what developers call the "Pyramid of Doom," where code drifts further and further to the right of the screen.
Nested logic is difficult to test because every "branch" doubles the number of scenarios you have to check. A script with four independent if/else checks has 16 possible paths ($2^4$). If you can keep your logic "flat"—by using else if or by dealing with errors early and exiting—your code will be significantly easier to maintain three months from now.
Furthermore, every if statement you write is a promise that you understand every possible input. If you check if (weight > 20), you are assuming weight is a number. If a user enters the string "Twenty", your comparison weight > 20 will result in false without an error, which might be the wrong business decision.
In the interview
In a professional interview, you will rarely be asked "What is an if statement?" Instead, an interviewer will probe your understanding of Equality and Truthiness.
The Question: "What is the difference between == and === in JavaScript, and which should you use?"
A weak answer: "=== is more strict and == is loose. You should use === because it's better." This is weak because it doesn't explain why or what the mechanism is.
A strong answer: "=== is the strict equality operator. It checks both the value and the type of the operands without performing type coercion. == is the loose equality operator, which attempts to convert the operands to a common type before comparing. In production code, we prefer === because type coercion in == can lead to unexpected results, such as the empty string being equal to the number zero."
Seniority levels:
- Junior: Expected to know that
===is preferred and can explain the basic syntax of anif/elseblock. - Senior: Will discuss "falsy" values and how to handle edge cases (like
nullorundefined) to prevent the script from crashing. They will also mention avoiding deeply nested conditions to keep code readable. - Lead/Manager: Will focus on the business logic risk. They want to know how you ensure that the logic covers all requirements and how you handle "default" states when no conditions are met.
Your tasks
- The Temperature Warning: Write a script where a variable
temperatureis set to a number. If it is above 30, print "Stay hydrated". If it is below 10, print "Wear a coat". Otherwise, print "Enjoy the weather". -
The Broken Comparison: Copy the following code into a file and run it. It will not work as expected. Fix the comparison so it correctly identifies when the
statusis "active".
let status = "inactive"; if (status = "active") { console.log("System is running"); } else { console.log("System is down"); } The Login Validator: Create a script with two variables:
usernameandpassword. Ifusernameis exactly "admin" ANDpasswordis "12345", print "Welcome, Admin". Otherwise, print "Login failed".The Truthiness Test: Create a variable
userInputand set it to an empty string"". Write anif/elsestatement that checks if the string is empty. Note: You can check the length of a string usinguserInput.length. If the length is 0, print "Please enter a name".
Your tasks this week
Do the exercises above before the next chapter. Reading a tutorial and doing
one are different activities and only one of them changes what you can build.
Stuck on any of them? Say so — describe what you tried and what happened:
tell me where you got stuck. I read every one, and the questions
that come back more than twice get answered in the next chapter.
JavaScript from absolute zero
Chapter 3 of 14. New chapter every Tuesday morning.
Next: Repeating work: loops and the array methods that replace them.
· The full syllabus and every chapter so far
· Subscribers also get the condensed notes for this chapter, the running
recap of everything the series has covered, and the extended guidance:
subscribe
Written by Amit Chakraborty — founding engineer and senior architect: React Native, AI and RAG systems, production architecture. Portfolio · LinkedIn · GitHub.
Need this built, reviewed or taught to your team? Get in touch or email amit@devamit.co.in. Available for senior and founding engineering roles, consulting and training, remote worldwide.