Coding Newbie

JavaScript Fundamentals: how to Understand if / else statements

IF / ELSE Statements in JavaScript are the basic way of manipulating the actions of your code. With properly specified If / Else conditions, you will be in position to control what your code does and to make your code more efficient.

If you are interested to learn about JavaScript array methods, you are more than welcome to read more about them Most Important JavaScript Array Methods.

If / Else Syntax

If / Else syntax consists of code blocks, and each of them runs when declared condition is met.

Syntax:

if (condition) {
// Run code if condition is true
} else {
// Run this code in all else situations
}

The condition inside IF signals JavaScript what condition to check for before continuing with the code. If that condition is true, JavaScript executes the code within the IF code block.

If the condition evaluates to false, JavaScript proceeds to ELSE part and executes code inside the ELSE code block.

Let’s say you need to check if the number entered is greater than 10. If that is the case, your code would look like this:

if (x > 10) {
    console.log("Number is greater than 10!");
} else {
    console.log("Number is lower than 10!");
}

What if you have to check multiple conditions?

In some cases you will need to check if several conditions were met, in order to determine which code block program should run. If that is the case, we use ELSE IF statements.

ELSE IF statements go between IF and ELSE part of code. It allows you to specify additional conditions. ELSE IF part of code runs when IF condition is false, but ELSE IF condition returns true.

Syntax:

if (condition) {
// Run code if condition is true
} 
else if(new condition) {
// Run this code if new condition is true
}
else {
// Run this code in all else situations
}

Note: You can add how as many ELSE IF statements as you need.

If we implement this in our previous example, it can look something like this:

if (x > 10) {
    console.log("Number is greater than 10!");
} 
else if (x > 5) {
     console.log("Number is between 5 and 10!");
}
else {
    console.log("Number is lower than 5!");
}

Declaring Conditions

In order to run code if condition is met, JavaScript uses return values of true and false. If condition returns true, JavaScript runs code block. If condition is not met and returns false, code continues further.

To check a condition, we use Comparison Operators.

There are four main types of comparison operators:

  1. Greater than (>)
  2. Greater or equal t(>=)
  3. Smaller than (>)
  4. Smaller or equal t(<=)
  5. Equal (==)
  6. Strictly equal (===)
  7. Unequal (!=)
  8. Strictly unequal (!==)

Conclusion

In this article we have learned what are IF, ELSE IF, and ELSE statements.

IF, ELSE IF and ELSE statements are used to control what actions your code performs in specific situations. It is a basic way to manipulate your code flow and control its actions.

%d bloggers like this: