const - JS | lectureJavaScript Fundamentals 1

IF/ELSE Statements

JavaScript Fundamentals 1

To start this lecture, let's say we want to create a program that checks whether a person has reached his/her retirement age ( We will assume retirement age to be 62 ). If the person has reached retirement age, then the program will print a message to the console. If the person hasn't, then it will print the number of years left before retirement.

script.js
const ageJacob = 65
const hasReachedRetirementAge = ageJacob >= 62/**
 * You can also write if(ageJacob >= 62)
*/
if(hasReachedRetirementAge) {    console.log('Jacob has reached retirement age!')
} else {    const yearsLeftBeforeRetirement = 62 - ageJacob
    console.log(`Jacob is left with ${yearsLeftBeforeRetirement}years before retirement!`)
}

From the above code snippet, you have noticed that I highlighted three lines. The first line provides a boolean value that we can use to make decisions using an if statement. Within the parenthesis, we provide a condition that is going to be evaluated. If the provided condition turns out to be true, then the if block will be executed.

script.js
if(condition) {    /**
     * Every line of code present here 
     * will be executed if condition is true
    */
}

In our program, the condition that we are checking is hasReachedRetirementAge. So, if we try to run our script, we are going to have, as result, Jacob has reached retirement age! which means our condition was true, thus executing the if block.

The else block, on the other hand, will be executed whenever the condition in the if parenthesis is false.

script.js
if(condition) {    /**
     * Every line of code present here 
     * will be executed if condition is true
    */
} else {
    /**
     * Every line of code present here 
     * will be executed if condition is false
    */
}

Let's update the value of ageJacob to say 60. Doing so will make the condition false because 60 isn't greater than or equal to 62, making the else block to be executed instead of the if block.

Keep in mind that the else block is optional. If there is no else block, JavaScript will then move on to the next line after the if statement if the condition is false.

The if/else statement is one of the most important things in programming because we make decisions with code all the time, which is essentially what we did in our example at the beginning; so that we can execute certain parts of our program based on certain conditions.

An if/else statement is also referred to as a control structure because this structure allows us to have more control over how our code is executed. In an if/else statement, the whole code does not execute all the code linearly. Instead, we can now control blocks of code that should execute and blocks that shouldn't. Thus giving us more control over how our code works. That's why it is called a control structure.