Menu Home

if

Hi everyone, and welcome to another edition of Boring JavaScript! Today, we tackle the ‘if’ statement. Throw away those sleeping pills and let’s dive right in.

Skip the reading: See the video.

If I Had A Hammer

The “if” statement is a fundamental statement for about every computer language out there (yes, even in Assembly – though under different names). The operation of an “if” statement is basic: Test the variable or expression to see if it’s True or False. When it’s True, execute that series of statements within the curly-cue brackets (the block), otherwise skip it.

And that’s pretty much it. Let’s look at an example:

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const myAnimal = animals[Math.floor(Math.random() * animals.length)];
if (myAnimal === "Cat") {
	console.log('\nMy animal is a Cat!');
}

Line 6 shows how to use the “if” statement. There are two important parts:

  1. The variable or condition to check. This must always be within parenthesis, and should evaluate to a Truthy or Falsey value (more on this later).
  2. The code to execute if the evaluation of the condition in #1 above is Truthy. These statements are within a block of curly-cue brackets. The brackets are optional, but be aware that if you don’t have the brackets, then the next line only will get executed. My recommendation is to always use brackets in order to make your intentions clear.

What Else Is There?

The statements within the first set of curly-cue brackets are executed if the condition is Truthy, but what about Falsey? That’s the job of the “else” statement. It is paired with an “if” and executed if the condition is Falsey.

Let’s take a look:

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const myAnimal = animals[Math.floor(Math.random() * animals.length)];
if (myAnimal === "Cat") {
	console.log('\nMy animal is a Cat!');
} else {
	console.log(`\nMy animal is NOT a Cat! It's a ${myAnimal}.`);
}

Same code as before – but notice Line 8. It contains the “else” statement, and completes a full rendering of the “if/else” construct. It follows the same rules concerning the curly-cue brackets as did the “if” statement – except that the “else” executes if the condition if Falsey.

Stacks upon Stacks upon Stacks

There is a third construct in which you can chain one “if” after another – and that’s the “else if” construct.

It fixes code that looks like this:

if (myAnimal === "Cat") {
    console.log(`\nMy animal is a Cat`);
} else {
    if (myAnimal === "Dog") {
        console.log(`\nMy animal is a Dog`);
    } else {
        if (myAnimal === "Horse") {
            console.log(`\nMy animal is a Horse`);
        } else {
            console.log(`\nMy animal is NOT any of those! It's a ${myAnimal}.`);
        }
    }
}

You see how quickly the above code can become a mess. But you can organize it using the “else if” statement.

if (myAnimal === "Cat") {
    console.log(`\nMy animal is a Cat`);
} else if (myAnimal === "Dog") {
    console.log(`\nMy animal is a Dog`);
} else if (myAnimal === "Horse") {
    console.log(`\nMy animal is a Horse`);
} else {
    console.log(`\nMy animal is NOT any of those! It's a ${myAnimal}.`);
}

The two code snippets above do the exact same thing – except that the last one is much easier to understand. And all because of “else if”.

The Truth about Truthy and Falsey

So what’s all this about “Truthy” and “Falsey”?

The condition with the “if” statement doesn’t evaluate just on the Boolean True or Boolean False – it uses a concept call “Truthy” or “Falsey”. Since JavaScript is a weakly-typed language, JavaScript will attempt to determine from your variable or expression that, if it was converted to Boolean, would the variable or expression become True or False.

This means that other variables or expressions can generate a Truthy (meaning, evaluates to True) or Falsey (meaning, evaluates to False) value. Here is a list of all ‘Falsey’ conditions.

  1. false – the actual word ‘false’
  2. 0 – the number zero
  3. “” – an empty string
  4. null – the null value
  5. undefined – any undefined value
  6. NaN – a ‘NaN’ value
  7. 0n – Bigint 0

Anything other than the above is ‘Truthy’.

Amazingly, if you create a variable using the Boolean class, it will always be truthy! Don’t believe me? Try the below:

const myBoolean = new Boolean(false);
if (myBoolean) {
    console.log('myBoolean is Truthy');
}

The above outputs the console.log. Why? Because what is assigned to the variable is not the value of the instance of the Boolean class, but the instance itself. And since an instance of an object is not in the list above, the value will always be Truthy.

By the way, using ‘myBoolen.valueOf()’ will give you the actual value, so if the “if” statement was written this way:

const myBoolean = new Boolean(false);
if (myBoolean.valueOf()) {
    console.log('myBoolean is Truthy');
}

…there will be no console.log output.

The video

As always, here is the video explaining the above.

Shameless Plug

You can find us all over the web!

Facebook

YouTube

Twitter

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: