Course

'if' Statement

Loading...

In this lesson, you'll learn about the statement in JavaScript, a fundamental concept for controlling the flow of logic in your programs.

Statement

You might have read the title of the current section, "Logic and Control Flow" and wondered what it means. It's much simpler than it may seem.

In every programming language, we have something known as an statement .

An if statement consists of a condition that is evaluated to either or and a block of code. If the condition is , then the code inside the block will run; otherwise, it's going to be skipped. It's that simple. Let's explore it in an example:

Imagine a nightclub that only allows people over the age of 18 to enter.

const age = 18;

if (age >= 18) {
   console.log('You may enter, welcome!');
}

Statement

statements can also have and statements. To continue with our example:

const age = 18;

if (age >= 18) {
    console.log('You may enter, welcome!');
} else if (age === 18) {
    console.log('You just turned 18, welcome!');
}

Notice how we have another condition there. If we run this code, what do you expect to see in your console?

Some of you might expect the code that's under the statement, but currently, that would not be the case. Let's test it out.

Why did the first block get logged out? For a really simple reason. It was the first one to pass the check. Our first condition specified that the age must be more than or equal to 18. 18 is indeed equal to 18. So how could we fix this? We can simply change the condition to just a greater than sign.

Statement

But what if the person is younger than 18? We currently aren't handling that case. That's where the  statement comes in handy. We implement it like this:

const age = 18;

if (age > 18) {
    console.log('You may enter, welcome!');
} else if (age === 18) {
    console.log('You just turned 18, welcome!');
} else {
    console.log('Go away!');
}

Try noticing the difference between the and the compared to the statement. Can you see it?

  • An statement does not have a condition.
  • If nothing is matched, is executed.
  • does not need a condition.
  • Simply, if none of the other conditions evaluate to , runs.

That's it! You've just learned one of the key concepts of all programming languages! Congrats! 😊

Loading...

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Truthy/Falsy Values