Making Decisions with Javascript II: Conditionals

In JavaScript, we use conditionals to perform actions based on different conditions. When we make decisions in code, to print out a result, we use conditionals.

The following are conditional statements in javaScript:

1.If: This statement only runs code if it's true. If you have some condition and it evaluates to true, the code will execute. If it evaluates to false, the code will not execute.

Example: let age=18;

if(age===18){ console.log (“You are allowed”); }

For instance, Let's assume you need to be a certain age to log on to a site, and the age required to register is “18”. What this syntax means is, ​if the age is strict “18”, the result should be “You are allowed”. This code will be executed because the condition evaluates to true. If the age is less or more than “18” the code will not be executed.

2.Else If: This statement only runs if the “if” statement is false. let score=5;

if (score===4) { console.log(“you did okay”); } else if (score===5) { console.log(“perfect score”); }

In this case, if the first condition is tried and it's false, try this next condition. You can have multiple else if conditions but it will come after if or other else if conditions.

Else: This is the last part of a condition and it is used if nothing else is true. In other words, if every possible option is false, use else. But, if other options are true else will not be executed.

Example: If a score is less than 10, create a “poor” result, if not, but score is less than 20, create a “Good ” result, otherwise an “excellent” result:

if (score < 10) { result= “poor”; } else if (score < 20) { result = “Good “; } else { result = “excellent”; }

These are just a few examples of conditional statements. It can be a great deal when working with more complex lines of code. This article covers the basics in order to acquaint you with how to use them, and which statement precedes the other.