Conditional Statements in JavaScript : if, else if, else.

Posted by

Conditional statements control behavior of function in JavaScript and determine whether or not pieces of code or function can run.

There are multiple different types of conditionals in JavaScript including:

  • “If” statements: where if a condition is true it is used to specify execution for a block of code.
  • “Else” statements: where if the same condition is false it specifies the execution for a block of code.
  • “Else if” statements: this specifies a new test if the first condition is false.

Now that you have the basic JavaScript conditional statement definitions, in image you can see how code executive in both conditions.

Here’s what’s happening in the example above:

  • The keyword if tells JavaScript to start the conditional statement.
  • (c == 0) is the condition to test, which in this case is true — input year is divided by 4 and reminder is 0.
  • The part contained inside curly braces {} is the block of code to run.
  • Because the condition passes, the variable outcome is assigned the value “leap year”.

Else Statement Example

You can extend an if statement with an else statement, which adds another block to run when the if conditional doesn’t pass.

EXAMPLE

In the same used example bove if the input vaue put by user not meet the mentioned condition, then the outcome is “not a leap year”, which is set if the consition if false.

Else if Condition

The else if statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions. There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.

Example:-

Above example is as if user input three required number as n1, n2, n3. When program run it chec the mentioned condition that which one is true according to the input. When the if statement is false, the computer will move onto the else if statement. If that is also false, then it will move onto the else block.

Copy and run this example to understand it better.

I hope you like particular information helpful about Conditions in JavaScript.

Keep practising and Exploring.

Thank You!!