Skip to content

Control Flow

Jacob Mai Peng edited this page Jun 9, 2021 · 2 revisions

Conditionals

if statements in JavaScript look the same as if statements in C and Java:

if (true) {
    console.log('The statement was true.');
}

/* The conditions can be any value. The bodies of falsy conditions won't execute. */
if (NaN) {
    console.log("This won't execute");
} else if (null) {
    console.log("Also won't execute");
} else // Note the omission of the curly braces here.
    console.log("This WILL be printed!");

Note that the parentheses around the condition are required. If the body of your if statement only has one line, you can omit the curly braces. This is sometimes a source of bugs, so I recommend always including them.

In Python, the equivalent would be:

if True:
    print('The statement was true.')

if False:
    print("This won't execute")
elif None:
    print("Also won't execute")
else:
    print("This WILL be printed!")

Ternary Conditionals

JavaScript also has the following way to express conditionals in one line:

const is_hot = true;
const drink = is_hot ? 'iced tea' : 'hot coffee';
console.log(drink); // 'iced tea'

This feature also exists in Java and C. The syntax is condition ? value if true : value if false. The important bits of syntax are the question mark ? and the colon :. This is how we'd express that same program using an if statement:

// If you're running these snippets one after the other, refresh the browser first to erase the old "is_hot" and "drink" variables.
const is_hot = true;

let drink;
if (is_hot) {
    drink = 'iced tea';
} else {
    drink = 'hot coffee';
}
console.log(drink); // Still 'iced tea'

Much longer, right? The ternary conditional operator allows us to express a conditional using fewer lines of code. Note that we also didn't have to reassign drink, so we could declare it const. Generally, declaring things const is good because you're less likely to change variables without meaning to (which is an infamous source of bugs in many languages!). We'll go deeper into this concept later.

Aside: Ternary Conditionals in Python

You may not know this, but Python also has ternary conditionals! Our drink example would look like this in Python:

is_hot = True
drink = 'iced tea' if is_hot else 'hot coffee' # Note that the syntax here has a different order than JS.

Nested ternary conditionals

You can also nest ternary conditionals, but doing this can quickly become unreadable and is generally not recommended.

const is_hot = true;
const is_thirsty = false;

// Can you make sense of what this statement is trying to do? It looks pretty confusing to me.
const drink = is_thirsty ? is_hot ? 'iced tea' : 'hot coffee' : 'nothing for me'
console.log(drink); // 'nothing for me'

Loops

while loops

Like Python, JavaScript has both for and while loops. While loops are pretty much the same as Python.

In Python:

i = 0
while i != 5:
    print(f"Sup! This is iteration #{i}")
    i += 1

In JavaScript:

let i = 0;
while (i != 5) {
    console.log(`Sup! This is iteration #${i}`);
    i += 1; // An equivalent way to write this is "i++;"
}

Just like if statements, the parentheses are required around the condition.

for loops

for loops are somewhat trickier, and they have more variations. Right now, we'll only cover the most basic variant. We'll revisit the other variants (for ... of and for ... in) when we cover Arrays and Objects.

The most basic variant doesn't really exist in Python, but it should look familiar if you have experience in Java or C:

// Again, "i++" is the same thing as "i += 1".
for (let i = 0; i < 5; i++) {
    console.log(`This is iteration #${i}`);
}

The syntax for your classic for loop is for (initialization ; exit condition ; increment). As you can see, there are three parts separated by semicolons:

  1. Initialization: this code runs before the start of the first loop.
  2. Exit condition: this code is checked at the end of each iteration. If it is truthy, the loop ends. Otherwise, the loop iterates again.
  3. Increment: this code runs after each iteration.

Footnote: loops in the real world

Loops are actually somewhat rare in everyday JS (A previous manager of mine who wrote JS every day said it had been years since he'd written a loop in it!). This is because the behaviour of loops can be implemented in other ways (using functions like map, filter, and reduce) that many JS developers find easier to read and less error-prone. We're covering loops here just so you're not lost if you do end up seeing one in the wild.

  • This is true for both the basic variant here and the for ... of and for ... in loops that we'll get to in a bit.

Clone this wiki locally