---
description: Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the condition is false, you can perform anothe
title: Conditional Statements in JavaScript: if, else, and else if
image: https://www.guru99.com/images/how-to-use-conditional-statements-in-javascript.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Conditional statements in JavaScript decide which block of code runs by testing a condition, and the if, if…else, and if…else if…else forms cover almost every branching decision that a beginner script will ever need.

* 🔘 **Syntax:** An if statement runs its block only when the condition inside the parentheses evaluates to true.
* ☑️ **Two branches:** The if…else form supplies a fallback block that runs whenever the condition is false.
* ✅ **Many branches:** Chaining else if tests several conditions in order and stops at the first match.
* 🧪 **Shorthand:** The ternary operator condenses a simple if…else into one expression that returns a value.
* 🛠️ **Alternative:** A switch statement compares one value against many fixed options more neatly than a long chain.
* 📊 **Pitfalls:** Falsy values, a stray assignment operator and missing braces cause most conditional bugs.

[ Read More ](javascript:void%280%29;) 

![Conditional Statements in JavaScript](https://www.guru99.com/images/conditional-statements-in-javascript.png) 

## JavaScript Conditional Statements

There are mainly three types of conditional statements in [JavaScript](https://www.guru99.com/introduction-to-javascript.html).

1. **if Statement**: An ‘if’ statement executes code based on a condition.
2. **if…else Statement**: The if…else statement consists of two blocks of code; when a condition is true, it executes the first block of code and when the condition is false, it executes the second block of code.
3. **if…else if…else Statement**: When multiple conditions need to be tested and different blocks of code need to be executed based on which condition is true, the if…else if…else statement is used.

Each of the three forms is examined below with its syntax and a runnable example. The same rules apply whether the script sits [inside the page or in an external file](https://www.guru99.com/all-about-internal-external-javascript.html), and whether the condition is written at the top level or inside a [function](https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html).

## How to Use Conditional Statements

Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the condition is false, you can perform another action.

The diagram below shows that idea as a fork in the road: a single condition is evaluated once, and control travels down the true branch or the false branch, never both.

[](https://www.guru99.com/images/JavaScript/javascript5%5F1.png)

## If Statement

**Syntax:**

if(condition)
{
	lines of code to be executed if condition is true
}

You can use `if` statement if you want to check only a specific condition. When the expression inside the parentheses evaluates to `true`, the block runs; when it evaluates to `false`, the interpreter skips straight past it and the script carries on with the next statement.

**Try this yourself:**

<html>
<head>
	<title>IF Statments!!!</title>
	<script type="text/javascript">
		var age = prompt("Please enter your age");
		if(age>=18)
		document.write("You are an adult <br />");
		if(age<18)
		document.write("You are NOT an adult <br />");
	</script>
</head>
<body>
</body>
</html>

The example asks the visitor for an age, then tests that value twice: once for 18 and above, once for below 18\. Because two separate `if` statements are used rather than an `else`, both conditions are evaluated every time the page loads.

**Modern equivalent:** the code above is kept exactly as published. In current JavaScript the same logic is normally written with `let` or `const` instead of `var`, with `console.log()` or `textContent` instead of `document.write()`, and without the `type="text/javascript"` attribute, which HTML5 makes optional.

## If…Else Statement

**Syntax:**

if(condition)
{
	lines of code to be executed if the condition is true
}
else
{
	lines of code to be executed if the condition is false
}

You can use the `if...else` statement if you have to check one condition and execute a different block of code for each outcome. Exactly one of the two blocks always runs, so no separate second test is required.

**Try this yourself:**

<html>
<head>
	<title>If...Else Statments!!!</title>
	<script type="text/javascript">
		// Get the current hours
		var hours = new Date().getHours();
		if(hours<12)
		document.write("Good Morning!!!<br />");
		else
		document.write("Good Afternoon!!!<br />");
	</script>
</head>
<body>
</body>
</html>

Here `new Date().getHours()` returns the current hour of the browser clock as a number from 0 to 23\. Any value below 12 produces the morning greeting, and every other value falls through to the `else` branch.

## If…Else If…Else Statement

**Syntax:**

if(condition1)
{
	lines of code to be executed if condition1 is true
}
else if(condition2)
{
	lines of code to be executed if condition2 is true
}
else
{
	lines of code to be executed if condition1 is false and condition2 is false
}

You can use the `if...else if...else` statement if you want to check more than two conditions. The conditions are evaluated from top to bottom, execution stops at the first one that is true, and the final `else` acts as a catch-all when none of them match.

**Try this yourself:**

<html>
<head>
	<script type="text/javascript">
		var one = prompt("Enter the first number");
		var two = prompt("Enter the second number");
		one = parseInt(one);
		two = parseInt(two);
		if (one == two)
			document.write(one + " is equal to " + two + ".");
		else if (one<two)
			document.write(one + " is less than " + two + ".");
		else
			document.write(one + " is greater than " + two + ".");
	</script>
</head>
<body>
</body>
</html>

Note the two calls to `parseInt()`. Values returned by `prompt()` are strings, so comparing them without conversion would compare text rather than numbers and would report “9” as greater than “10”.

### RELATED ARTICLES

* [JavaScript DOM Tutorial with Example ](https://www.guru99.com/how-to-use-dom-and-events-in-javascript.html "JavaScript DOM Tutorial with Example")
* [OOJS: Object Oriented JavaScript Tutorial with Example ](https://www.guru99.com/learn-object-oriented-javascript.html "OOJS: Object Oriented JavaScript Tutorial with Example")
* [Top 60 AJAX Interview Questions and Answers (2026) ](https://www.guru99.com/ajax-interview-questions.html "Top 60 AJAX Interview Questions and Answers (2026)")
* [Top 50 D3.js Interview Questions and Answers (2026) ](https://www.guru99.com/d3-js-interview-questions.html "Top 50 D3.js Interview Questions and Answers (2026)")

## Ternary Operator: A Shorthand for if…else

When an `if...else` block only chooses between two values, the conditional (ternary) operator expresses the same decision as a single expression. It is the one JavaScript operator that takes three operands: a condition, a question mark, the value used when the condition is truthy, a colon, and the value used when it is falsy.

// if...else form
let message;
if (age >= 18) {
  message = "adult";
} else {
  message = "minor";
}

// same decision as a ternary expression
let label = age >= 18 ? "adult" : "minor";

Use the ternary operator when it improves readability, not merely to save lines:

* **Good fit:** picking one of two values to assign, return, or drop into a template string.
* **Poor fit:** branches that run several statements, call functions for their side effects, or need their own local variables.
* **Avoid nesting:** a ternary inside a ternary is far harder to read than an `else if` chain.

## switch Statement vs if…else if…else

A long `else if` chain that keeps comparing the same variable against different fixed values is usually clearer as a `switch` statement. The switch evaluates its expression once, then jumps to the matching `case`; `break` stops execution falling through into the next case, and `default` plays the role of the final `else`.

switch (day) {
  case "Sat":
  case "Sun":
    document.write("Weekend");
    break;
  default:
    document.write("Weekday");
}

The two structures are not interchangeable in every situation:

| Point of comparison | if…else if…else                                           | switch                                              |
| ------------------- | --------------------------------------------------------- | --------------------------------------------------- |
| Kind of test        | Any boolean expression, including ranges such as hours<12 | Equality against fixed values only                  |
| Comparison used     | Whatever operator you write                               | Strict comparison, so "5" does not match 5          |
| Readability         | Best for a few unrelated conditions                       | Best for many values of one variable                |
| Common bug          | Forgetting the trailing else                              | Forgetting break, which lets execution fall through |

## Truthy and Falsy Values in JavaScript Conditions

A condition does not have to be a comparison. JavaScript converts whatever it finds inside the parentheses to a boolean first, which is why `if (name)` is valid code. Only six values convert to false: `false`, `0`, the empty string, `null`, `undefined`, and `NaN`. Everything else is truthy, including the string `"0"`, an empty array, and an empty object.

Most conditional bugs in beginner scripts come from a short list of mistakes:

* **Assignment instead of comparison:** `if (x = 5)` assigns and is always truthy; `if (x === 5)` compares.
* **Loose equality surprises:** `==` converts types before comparing, so `"" == 0` is true. Prefer `===`.
* **Missing braces:** without `{}` only the next single statement belongs to the branch, exactly as in the examples above.
* **Unconverted input:** values from `prompt()` and form fields are strings until `parseInt()` or `Number()` converts them.
* **Unreachable branches:** in an `else if` chain, place the narrowest condition first, or a broader earlier test will always win.

This code is editable. Click Run to Execute  

## FAQs

⚡ What is the difference between =, == and === in a condition?

A single `=` assigns a value and makes the condition truthy by accident. `==` compares after converting types, so `"" == 0` is true. `===` compares value and type together and is the safer default.

🧠 How can AI tools help you understand conditional logic?

AI assistants can restate an unfamiliar `else if` chain in plain English, suggest the input values that reach each branch, and flag a condition that can never be true. Always run the code yourself, because the explanation is a suggestion rather than proof.

🤖 Can GitHub Copilot write if…else chains for you?

Often yes. [GitHub Copilot](https://github.com/features/copilot) completes branching code from a comment or a partial condition. Check the boundary values it picks, since a generated `>` where you needed `>=` is easy to miss.

🔁 How deep can you nest branches inside each other?

There is no language limit. Any statement may appear inside a branch, including a further `if`. Beyond two levels the logic becomes hard to follow, so combine the tests with `&&` or return early instead.

🧩 Are curly braces required after if?

No. Without braces the branch owns only the next single statement, which is why the examples above work. Adding braces is still recommended, because a second line added later silently falls outside the branch.

🧮 How do && and || behave inside a condition?

`&&` is true only when both sides are truthy, and `||` is true when either side is. Both short-circuit: the right-hand side is never evaluated once the result is already decided.

🕒 Why does the greeting example call new Date().getHours()?

`getHours()` returns the current hour of the visitor’s own clock as a number from 0 to 23, so the comparison against 12 splits the day into morning and afternoon without any extra parsing.

📝 Is elseif written as one word in JavaScript?

No. JavaScript uses two separate keywords, `else if`, with a space between them. The single word `elseif` belongs to PHP and some template languages and raises a syntax error in a browser.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/how-to-use-conditional-statements-in-javascript.png","url":"https://www.guru99.com/images/how-to-use-conditional-statements-in-javascript.png","width":"484","height":"350","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/javascript","name":"JavaScript"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html","name":"Conditional Statements in JavaScript: if, else, and else if"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html#webpage","url":"https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html","name":"Conditional Statements in JavaScript: if, else, and else if","dateModified":"2026-07-29T17:11:42+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/how-to-use-conditional-statements-in-javascript.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/james","name":"James Hartman","description":"I am James Hartman, a seasoned professional in Oracle Certified Java Professional tutorials, specializing in crafting comprehensive guides to help you excel in your Java certification journey.","url":"https://www.guru99.com/author/james","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","url":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","caption":"James Hartman","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"@type":"NewsArticle","headline":"Conditional Statements in JavaScript: if, else, and else if","keywords":"javascript, java","dateModified":"2026-07-29T17:11:42+05:30","articleSection":"JavaScript","author":{"@id":"https://www.guru99.com/author/james","name":"James Hartman"},"publisher":{"@id":"https://www.guru99.com/#organization"},"description":"Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the condition is false, you can perform anothe","copyrightYear":"2026","copyrightHolder":{"@id":"https://www.guru99.com/#organization"},"name":"Conditional Statements in JavaScript: if, else, and else if","@id":"https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html#richSnippet","isPartOf":{"@id":"https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html#webpage"},"image":{"@id":"https://www.guru99.com/images/how-to-use-conditional-statements-in-javascript.png"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html#webpage"}}]}
```
