In JavaScript, conditional operators are used to make decisions based on certain conditions. The primary conditional operator in JavaScript is the if statement, which allows you to execute a block of code if a specified condition is true. Additionally, JavaScript also provides other conditional operators like else, else if, switch, and the ternary operator (? :). Here's a brief overview of each:
*if *:
if is a primary conditional operator in js.
syntax
if (condition) {
// Code to be executed if the condition is true
}else...if : when two fact which can be execute in a function than comes the else if as a solution
syntax
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
if...else if...else Statement: when there are more than two condition can be execute in a function then we used if...else if...else Statement it used for complex conditional rendering.
syntax
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if none of the conditions are true
}Switch Statement: switch statement is used in big or complicated conditional statement.
syntax
switch (expression) {
case value1:
// Code to be executed if expression === value1
break;
case value2:
// Code to be executed if expression === value2
break;
default:
// Code to be executed if expression doesn't match any case
}
5.Ternary Operator (Conditional Operator):
Now a day it's most popular and easy Conditional operator that can solve a large statement with a single line of code .
syntax :
(condition) ? expression1 : expression2;
// If the condition is true, expression1 is evaluated; otherwise, expression2 is evaluated.
Top comments (3)
There is a glaring typo in your header image
Thanks for your comment.
Thanks for the post!
I recommend wrapping your "syntax" sections in the code block, using three backticks. You can also provide formatting by specifying the type, like this:
This produces the following:
One of the things I didn't realize for some time in JavaScript was that
else if
isn't an operator at all)! Some languages do have a specific operator, like Python'selif
. Becauseif
andelse
take statements or blocks, theelse
accepts the followingif
statement. MDN's documentation provides a better explanation