Loading Please Wait...
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
Use ternary operator (?:) one liner alternative to if-else.
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
if (num > 0) {
alert('Number is positive');
}
Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
if (num > 0) {
alert('Number is positive');
} else {
alert('Number is 0 or negative');
}
Use the else if statement to specify a new condition if the first condition is false.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
if (num > 0) {
alert('Number is positive');
} else if(num < 0) {
alert('Number is negative');
} else {
alert('Number is 0');
}
We can use any level of nesting in if, else, and else if statements.
Take care of code block that is open and closing of each statements.
if (num > 0) {
alert('Number is positive');
} else {
if (num < 0){
alert('Number is negative');
} else {
alert('Number is 0');
}
}
JavaScript also contains a conditional (ternary) operator that assigns a value to a variable based on some condition.
variablename = (condition) ? value1 : value2
let result = (num > 0) ? "Number is positive" : "Number is 0 or negative";
How you feel about this blog:
Share this blog on:
If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com
Contact UsWe are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..
Copyright ©
, Lynxsia IT Solutions, All rights reserved