Run Code Only Sometimes With if

Every script you’ve written so far runs every line, top to bottom, each time. That’s fine for adding up a bill, but many everyday rules only apply some of the time. You plug in your phone when the battery is low. A shop waives delivery when your order is big enough.

In this course, you’ll teach your programs to make that kind of choice. By the end, you’ll write a day-trip ticket checker that reads a published rule table and decides which price applies, or whether an input is valid at all. It all starts with one small tool, the if statement, which runs a few lines only when a condition holds.

As in the earlier courses of JavaScript Basics, you type the examples into a script in VS Code, run them with node in the integrated terminal, and change values to see what happens.

Then an on-site exercise gives you practice with automatic feedback. Buttons like Quiz me with new battery values open a short conversation with the mentor, who gives you a new case and replies to your answer. They’re optional, and each one has a check-yourself alternative nearby.

If you’re joining here directly, you’ll need to know how to run a script and how comparisons like >= produce true or false. Later in the course, you’ll also use Number(), NaN, null, and undefined from Compare and Convert, with a short warmup when they return.

Warm Up With a Boundary

An if statement decides based on a Boolean value, and comparisons are the most common way to get one. First, recall how comparisons treat the exact boundary.

Start the Node.js REPL, where you can enter JavaScript and see each result right away, by running node in the terminal. Before you press Enter on each line below, predict whether it’ll give true or false:

Language: JavaScript
> 20 <= 20
true
> 20 < 20
false
> 21 <= 20
false

The <= operator includes the boundary itself, so 20 <= 20 is true. The < operator leaves it out, so 20 < 20 is false. The same goes for >= and >. A rule like “20 percent or less” means exactly 20 counts, and your code needs to agree. Leave the REPL with .exit when you’re done.

Write Your First if Statement

Here’s the rule you’ll turn into code. When your phone’s battery is at 20 percent or less, you want a reminder to find a charger. Whatever the level, you also want to see the current percentage.

In your course folder, create a new file named battery.js and type in this script:

Language: JavaScript Filename: battery.js
const batteryLevel = 15;

if (batteryLevel <= 20) {
  console.log("Battery low. Time to find a charger!");
}

console.log(`Battery at ${batteryLevel}%`);

The middle three lines are an if statement. It has three parts:

  1. The keyword if starts the statement.
  2. The condition in parentheses, batteryLevel <= 20, is an expression that gives true or false.
  3. The block in curly braces, { and }, holds the lines to run when the condition is true.

When the condition is false, JavaScript skips the whole block and carries on after the closing brace. The last line sits outside the braces, so it runs either way. Save the file and give it a spin:

Language: Shell
$ node battery.js
Battery low. Time to find a charger!
Battery at 15%

With a level of 15, the condition is true, so you get the reminder and then the percentage. Now find out what happens with a fuller battery. Change the first line so that the level is 64:

Language: JavaScript Filename: battery.js
const batteryLevel = 64;

if (batteryLevel <= 20) {
  console.log("Battery low. Time to find a charger!");
}

console.log(`Battery at ${batteryLevel}%`);

Save the file and run the script again:

Language: Shell
$ node battery.js
Battery at 64%

Nice! The reminder is gone because 64 <= 20 is false, so JavaScript skips the block. The percentage still shows up because that line comes after the closing brace.

Try two more values before you move on. Set the level to 20, run it, and then try 21. With 20, you’ll see the reminder because <= includes the boundary. With 21, you won’t. Checking the exact boundary and the value just past it is a habit that’ll pay off in every exercise of this course.

The indentation inside the braces is for people reading the code. JavaScript only looks at the braces to find where the block starts and ends. Indent each line inside a block by two spaces and line up the closing brace with the if, so that what you see matches what JavaScript runs.

Predict Which Lines Run

A script can contain several if statements. JavaScript checks each condition on its own as it reaches it, and the lines between and after the blocks always run. Replace the contents of battery.js with this version, which also knows whether the phone is plugged in:

Language: JavaScript Filename: battery.js
const batteryLevel = 45;
const isCharging = true;

if (isCharging) {
  console.log("Charging...");
}

if (batteryLevel === 100) {
  console.log("Fully charged. You can unplug now.");
}

console.log(`Battery at ${batteryLevel}%`);

The first condition is just the Boolean isCharging. It’s already true or false, so it doesn’t need a comparison. The second condition uses strict equality, ===, which you met when comparing values in Compare and Convert.

Before you run it, decide for each block whether its condition is true, and write down the lines you expect. Then run it to compare:

Language: Shell
$ node battery.js
Charging...
Battery at 45%

The first block ran because isCharging is true. The second was skipped because 45 === 100 is false. The last line ran as always.

Now give yourself a small challenge. Which values would print all three lines? Which would print only the percentage? Change the two values at the top, predict the output, and run the script to check. If your prediction and the output disagree, evaluate each condition by hand with your values.

Keep Values You Need Outside the Braces

Often you want a block to work out a value that you use after the if statement. Say you want a battery-saving tip when the battery is low and a calmer message when it isn’t.

There’s one rule to know first. A variable that you declare with let or const inside the braces belongs to that block. Once JavaScript reaches the closing brace, that name no longer exists.

So if you need a variable after the block, declare it before the if statement with a starting value that makes sense when the condition is false. Inside the block, you then only update it:

Language: JavaScript Filename: tip.js
const batteryLevel = 15;
let tip = "No action needed.";

if (batteryLevel <= 20) {
  tip = "Lower the screen brightness.";
}

console.log(tip);

Save it as tip.js and run it:

Language: Shell
$ node tip.js
Lower the screen brightness.

Change the level to 64 and run it once more. You’ll see No action needed. because JavaScript skips the block and tip keeps its starting value. You declare tip with let because the block may reassign it.

Now here’s a mistake that’s easy to make. This version declares tip inside the block instead. Before you run it, look at the last line and decide why it can’t reach tip, even though the level is 15 and the block runs:

Language: JavaScript Filename: tip-mistake.js
const batteryLevel = 15;

if (batteryLevel <= 20) {
  let tip = "Lower the screen brightness.";
}

console.log(tip);

Save it as tip-mistake.js and run it to check your answer:

Language: Shell
$ node tip-mistake.js
ReferenceError: tip is not defined

Whoops! The let tip line lives inside the braces, so the name stops existing at the closing brace, and the last line has nothing to print. When JavaScript says a name you declared is not defined, check whether its declaration sits inside a block that ends before the line using it. You’ll learn the full rules for where names are visible in the Functions course.

To check yourself without the mentor, picture a script that declares let status = "Unplugged"; before if (isCharging) { status = "Charging"; } and then logs status. With isCharging set to false, what prints? And what happens if the let moves into the block? You should get Unplugged, and then a ReferenceError for status.

Get Ready for the On-Site Exercise

The next item is an on-site coding exercise. You write your code right in the browser and press Run Tests to check it. The tests try your code with several inputs. When a case fails, compare the expected result in the failure message with the result your code gave, make one change, and run the tests again. Run them early and often. For more room, use the Full screen button, or press T when you aren’t typing in the editor.

Your code goes inside a short supplied wrapper. Here’s the battery tip from tip.js as it could look inside one:

Language: JavaScript
function getTip(batteryLevel) {
  let tip = "No action needed.";

  if (batteryLevel <= 20) {
    tip = "Lower the screen brightness.";
  }

  return tip;
}

The first line, with the input name batteryLevel in parentheses, and the return line are supplied. You leave them as they are. The part you write is the decision in between, which works just like your local script.

Each test call supplies a different value for batteryLevel. When a test calls getTip(15), the condition 15 <= 20 is true, so the block updates tip, and the return line hands "Lower the screen brightness." back to the test runner.

When a test calls getTip(64), the condition is false, so tip keeps its starting value and "No action needed." is returned. The runner compares each returned value with the expected answer. A console.log() line would only display text, which the tests don’t check.

The exercise’s wrapper might also start with export, supplied wiring that lets the runner find the function. Leave it as it is.

Next up, you’ll put this to work in Unlock Free Delivery, where an order gets free delivery once it reaches a stated amount. Keep an eye on that boundary!

Become a Member to join the conversation.