There are the following types of Javascript if/else Statement Syntax.
Javascript if statement is used to check the given condition is true or not. If the condition is true then execute the block of code.
if (condition) {
//statement
}
if (condition == true) {
//execute the code
}
Source Code
var developmentExperienceYears = 10;
if (developmentExperienceYears > 5) {
document.write("You are able to open your own startup.");
}
If..else statement is used to execute the block of the code if the certain condition is false.
if (expression) {
//The code will be executed if condition is true
} else {
//The code will be executed if condition is false
}
Source Code
var itIndustryExperience = 2;
if (itIndustryExperience > 3) {
document.write("You may try own startup");
} else {
document.write("Please learn through the mistake.");
}
This statement is used to check new conditions if the previous condition is false.
if(condition1){
//code will be executed if first condition is true
}
else if(condition2){
//code will be executed iffirst condition is false and second condition is true
}else{
//code will be executed if first condition is false and second condition is false
}
Source Code
var itIndustryExperience = 8;
if (itIndustryExperience < 3) {
document.write("Please learn through the mistake.");
} else if (itIndustryExperience < 6) {
document.write("You may try for own startup");
} else {
document.write("You must have to work for own startup");
}
It is shorthand of if..else statement and represented by a question mark(?) and takes three operands for checking the condition, a result for true, and a result for false.
var result = (condition) ? value1 : value2;
If the condition is true then value 1 will be returned else value 2 will be returned.
Source Code
var developmentExperience = 8;
var result = (developmentExperience<5)?"Learn":"Try for startup";
Code Explanation
In the above code, the condition is false so the value on the right side of the colon (:) is returned to the variable result;