- JavaScript if, else, and else if
- Conditional Statements
- The if Statement
- Syntax
- Example
- The else Statement
- Example
- The else if Statement
- Syntax
- Example
- More Examples
- JavaScript if. else
- Parameter Values
- More Examples
- Related Pages
- Browser Support
- if. else
- Try it
- Syntax
- Description
- Examples
- Using if. else
- Using else if
- Using an assignment as a condition
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- When to Use the if Statement to Program HTML with JavaScript
- How to create a simple if statement in JavaScript
- What else can you do with the if statement?
- How to nest if statements in JavaScript
JavaScript if, else, and else if
Conditional statements are used to perform different actions based on different conditions.
Conditional Statements
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
The switch statement is described in the next chapter.
The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
Example
Make a «Good day» greeting if the hour is less than 18:00:
The result of greeting will be:
The else Statement
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
>
Example
If the hour is less than 18, create a «Good day» greeting, otherwise «Good evening»:
The result of greeting will be:
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
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
>
Example
If time is less than 10:00, create a «Good morning» greeting, if not, but time is less than 20:00, create a «Good day» greeting, otherwise a «Good evening»:
if (time < 10) <
greeting = «Good morning»;
> else if (time < 20) <
greeting = «Good day»;
> else <
greeting = «Good evening»;
>
The result of greeting will be:
More Examples
Random link
This example will write a link to either W3Schools or to the World Wildlife Foundation (WWF). By using a random number, there is a 50% chance for each of the links.
JavaScript if. else
The if statement specifies a block of code to be executed if a condition is true:
The else statement specifies 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
>
The else if statement specifies 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
>
Parameter Values
More Examples
If time is less than 10:00, create a «Good morning» greeting, if not, but time is less than 20:00, create a «Good day» greeting, otherwise a «Good evening»:
var time = new Date().getHours();
if (time < 10) greeting = "Good morning";
> else if (time < 20) greeting = "Good day";
> else greeting = «Good evening»;
>
If the first element in the document has an id of «myDIV», change its font-size:
var x = document.getElementsByTagName(«DIV»)[0];
if (x.id === «myDIV») <
x.style.fontSize = «30px»;
>
Change the value of the source attribute (src) of an element, if the user clicks on the image:
Display a message based on user input:
var letter = document.getElementById(«myInput»).value;
var text;
// If the letter is «c»
if (letter === «c») text = «Spot on! Good job!»;
// If the letter is «b» or «d»
> else if (letter === «b» || letter === «d») text = «Close, but not close enough.»;
// If the letter is anything else
> else text = «Waaay off..»;
>
// Get the value of the input field with >x = document.getElementById(«numb»).value;
// If x is Not a Number or less than 1 or greater than 10, output «input is not valid»
// If x is a number between 1 and 10, output «Input OK»
if (isNaN(x) || x < 1 || x >10) text = «Input not valid»;
> else text = «Input OK»;
>
Related Pages
Browser Support
if. else is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
if. else
The if. else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed.
Try it
Syntax
if (condition) statement1 // With an else clause if (condition) statement1 else statement2
An expression that is considered to be either truthy or falsy.
Statement that is executed if condition is truthy. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement ( < /* . */ >) to group those statements. To execute no statements, use an empty statement.
Statement that is executed if condition is falsy and the else clause exists. Can be any statement, including block statements and further nested if statements.
Description
Multiple if. else statements can be nested to create an else if clause. Note that there is no elseif (in one word) keyword in JavaScript.
if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 // … else statementN
To see how this works, this is how it would look if the nesting were properly indented:
if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 // …
To execute multiple statements within a clause, use a block statement ( < /* . */ >) to group those statements.
if (condition) statements1 > else statements2 >
Not using blocks may lead to confusing behavior, especially if the code is hand-formatted. For example:
function checkValue(a, b) if (a === 1) if (b === 2) console.log("a is 1 and b is 2"); else console.log("a is not 1"); >
This code looks innocent — however, executing checkValue(1, 3) will log «a is not 1». This is because in the case of dangling else, the else clause will be connected to the closest if clause. Therefore, the code above, with proper indentation, would look like:
function checkValue(a, b) if (a === 1) if (b === 2) console.log("a is 1 and b is 2"); else console.log("a is not 1"); >
In general, it is a good practice to always use block statements, especially in code involving nested if statements.
function checkValue(a, b) if (a === 1) if (b === 2) console.log("a is 1 and b is 2"); > > else console.log("a is not 1"); > >
Do not confuse the primitive Boolean values true and false with truthiness or falsiness of the Boolean object. Any value that is not false , undefined , null , 0 , -0 , NaN , or the empty string ( «» ), and any object, including a Boolean object whose value is false , is considered truthy when used as the condition. For example:
const b = new Boolean(false); if (b) console.log("b is truthy"); // "b is truthy" >
Examples
Using if. else
if (cipherChar === fromChar) result += toChar; x++; > else result += clearChar; >
Using else if
Note that there is no elseif syntax in JavaScript. However, you can write it with a space between else and if :
if (x > 50) /* do something */ > else if (x > 5) /* do something */ > else /* do something */ >
Using an assignment as a condition
You should almost never have an if. else with an assignment like x = y as a condition:
However, in the rare case you find yourself wanting to do something like that, the while documentation has a Using an assignment as a condition section with an example showing a general best-practice syntax you should know about and follow.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 5, 2023 by MDN contributors.
Your blueprint for a better internet.
When to Use the if Statement to Program HTML with JavaScript
You really can’t escape using the if statement with JavaScript. The if statement is commonly used for testing whether something has happened or not, whether the data is in range or not, or whether the user wants to perform a specific task.
How to create a simple if statement in JavaScript
One of the most common uses of the if statement is to make a simple selection. When the user takes a particular action, something happens. In the following example, when the user clicks OK in the confirm dialog box, the application displays the secret message.
// Create an expression that results in true or false. var Answer = confirm( "Do you want to display the secret message?"); // Test the expression using the if statement. if (Answer) < // Display the secret message when the user // clicks OK. document.getElementById("Result").innerHTML = "This is the secret message!"; >
In this case, Answer can contain only true or false because confirm() doesn’t output any other values. As a consequence, you don’t need to perform any sort of value checks on Answer — all you need to do is determine the truth value of Answer to make the decision.
All decision making expressions that you ever create will have a truth value of some sort — either true or false. Sometimes the truth value is hidden, as when working with the switch structure, but the truth value is there.
Computers don’t understand anything other than true or false. There are techniques that make it appear that the computer can do something else, but in reality, it all comes down to making a true or false decision as shown here.
What else can you do with the if statement?
You use the if statement in situations when an application needs to do something when the user responds correctly, but ignore the input when the response is incorrect. However, there are times when you must do something when the input is correct and something else when it’s incorrect. In this case, you add the else clause to the if statement as shown in the following example.
// Create an expression that results in true or false. var Answer = confirm( "Do you want to display the secret message?"); // Test the expression using the if statement. if (Answer) < // Display the secret message when the user // clicks OK. document.getElementById("Result").innerHTML = "This is the secret message!"; >else < // Perform an alternative task. alert("Click OK next time to see the message!"); >
A clause is an extension of a structure. In this case, the else clause extends the if structure to include a second code block that handles the false condition. The example still outputs the secret message when the user clicks OK in the confirm() dialog box.
However, now the code also displays an alert() dialog when the user clicks Cancel. This secondary action helps the user understand how to react to the confirm() dialog box to obtain a different output.
How to nest if statements in JavaScript
There are many reasons why you might nest if statements — that is, place one if statement within another. In this case, the user selects an option onscreen, CheckChoice() performs a check of that option, and then CheckChoice() displays the correct result onscreen.
function CheckChoice(option) < // Verify that the input is a number. if (typeof(option) != "number") < // Display an error dialog. alert("Please provide numeric input!"); // Return without doing anything more. return; >// Ensure that option is actually an integer. var Select = Math.round(option); // Verify that the input is in range. if ((Select < 1) || (Select >3)) < // Display an error dialog. alert("The value supplied is out of range!"); // Return without doing anything more. return; >// Make a selection. if (Select == 1) < document.getElementById("Result").innerHTML = "You chose Item A."; >else < if (Select == 2) < document.getElementById("Result").innerHTML = "You chose Item B."; >else < document.getElementById("Result").innerHTML = "You chose Item C."; >> >
This example doesn’t rely on a known source of input, so it begins by performing various checks of the data. The first check verifies that the caller has supplied a numeric value. After all, the caller could provide a string or a Boolean value instead. For that matter, the input could be a pointer to another function or anything else that JavaScript supports — you just don’t know.
The next step converts the numeric input to an integer. Data conversion is important in JavaScript because it treats both integers and floating point values as numbers. If you want an integer value, using Math.round() to get it is the best way to go. This function rounds the input to the nearest integer value, which means you don’t end up trying to perform comparisons against values such as 3.5 .
At this point, you know you have a number and that the number is an integer, but you don’t know whether the number is in the correct range. A failure to range-check input values is the cause of many woes in JavaScript applications. CheckChoice() is expecting integer values in the range of 1 to 3, so the range check looks for these values.
The nested if statement is almost anticlimactic at this point. You know that Select contains 1 , 2 , or 3 . The first if statement checks for a value of 1 and displays a message when it finds that value. When the value is something other than 1, the else clause takes over. Within the else clause is a nested if statement.
This if statement checks Select for a value of 2 and displays the appropriate message when it is. When Select is 3 , the else clause of this second, nested, if statement displays the appropriate message.