🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to JavaScript Notes
Topic #18

JS If Else


The else Statement

Use the else statement to specify a block of code to be executed if a 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 (hour < 18) {

    greeting = "Good day";

 }
else {

    greeting = "Good evening";

 }

The else if Statement

Use the else if statement to specify a new condition if the first 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 < 10) {

    greeting = "Good morning";

 }
else if (time < 20) {

    greeting = "Good day";

 }
else {

    greeting = "Good evening";

 }

Example

let text;

if (Math.random() < 0.5) {

  text = "<a href='https://w3schools.com'>Visit W3Schools</a>";

} else {

  text = "<a href='https://wwf.org'>Visit WWF</a>";

}

document.getElementById("demo").innerHTML = text;

Want to go beyond the notes?

Join CodingNow 2.0's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

JS If Else – FAQs

Quick answers about learning JS If Else in JavaScript.

This free note from CodingNow 2.0 explains JS If Else in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on CodingNow 2.0, including JS If Else, is 100% free with no signup required.
With focused practice, most students grasp JS If Else in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now