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!!