DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • 5 Layers of Prompt Injection Defense You Can Wire Into Any Node.js App
  • Boosting React.js Development Productivity With Google Code Assist
  • Why Angular Performance Problems Are Often Backend Problems

Trending

  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • How to Write for DZone Publications: Trend Reports and Refcards
  • Compliance Automated Standard Solution (COMPASS), Part 11: Compliance as Code, the OSCAL MCP Server Way
  • The Agentic Agile Office: Streamlining Enterprise Agile With Autonomous AI Agents
  1. DZone
  2. Coding
  3. JavaScript
  4. Conditionals In JavaScript

Conditionals In JavaScript

In this blog, you'll learn about conditional statements in JavaScript, including if, else, else if, switch, and ternary operators for decision-making.

By 
Shashank Sharma user avatar
Shashank Sharma
·
Apr. 24, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
4.4K Views

Join the DZone community and get the full member experience.

Join For Free

Conditional statements are used for making decisions based on different conditions. Also, conditionals in JavaScript allow you to execute different blocks of code based on whether a certain condition is true or false.

Conditions can be implemented using the following ways:

  • If
  • If Else
  • Else If
  • Switch
  • Ternary operators

If Statement

This statement shows truthy values used to check if the given conditions are true and then execute the block of code. 

JavaScript
 
  if(condition){
  -----block of code which is going to execute-----
  }


Let's understand this with an example.

JavaScript
 
let num = 10
if (num > 0) {
console.log(num + "is a positive number")
} 
//Output => 10 is a positive number//
//In the above example, we set the condition that if the user enters any number greater than 0, then "if" condition got executed and it returns the output.//


Else Statement

It's the opposite of an If statement. So we will say that, if the If condition is not executed, which will happen when the given condition is false, then the Else statement gets executed.

JavaScript
 
if(condition){
-----block of code which is going to execute-----
} else {
-----block of code which is going to execute-----
}


Let's take an example and try to understand this.

JavaScript
 
//lets say we made a google form for football trails and age limit for the peoples who can apply for this is 16+. Now, If the user enter age more or less than the given age, certain blocks of code gets executed and give response accordingly.//
let myAge = 15
if (myAge > 16) {
console.log(myAge + " is valid age, you are eligible for trials.")
} else {
console.log(myAge + " is not a valid age, you are not eligible for the trials .")
}
//I Hope this clears how "If" and "Else" statements works//


Else If

This is used for most cases because there are multiple options to select from sometimes.

Let's understand this with an example.

JavaScript
 
  if(condition){
  -----block of code which is going to execute-----
  } else if(condition){
  -----block of code which is going to execute-----
  } else {
  -----block of code which is going to execute-----
  }


Let's say we found an interesting website, and in order to get the most out of this website, it's asking us to make an account on it. As we are going through the process of making an account, it asks us to set questions and answers in case we lose our password so we can still be able to log in by giving the correct answer to the questions. Now, a few months pass and we want to sign in to that website but we couldn't remember our password, so the website gives us the option to sign in by giving answers to the questions we set previously. It gives us a question and four options to choose from.

Que: What is your favorite color?

a) blue

b) Indigo

c) pink

d) red

JavaScript
 
let favColor = 'blue'
if(favColor === 'indigo'){
console.log("indigo is not your favorite color.Try again") 
} else if(favColor === 'pink'){
console.log("pink is not your favorite color.Try again")
} else if(favColor === 'red'){
console.log("Seriously, red, broooo Try again")
} else if(favColor === 'blue'){
console.log("Thats my bro, blue is your fav color. Never forget your password again.")
} else {
console.log("Enter your fav color")
}


Switch Statement

The switch statement is an alternative for If Else statements.

The switch statement makes the code more concise and easier to read when you need to test a single variable against multiple possible values.

JavaScript
 
  switch (case value) {
  case 1: 
     console.log('   ')
     break; //Suppose, the condition is satisfied after end of case 1, then, 'break' terminates the code//
  case 2:
     console.log('   ')
     break;

  default: //default runs only if all the cases dont satisfy conditions.//
     console.log(' ')
  }


Let's understand this with an example.

JavaScript
 
let theDay = 'tuesday'
switch(theDay) {
case'monday':
   console.log('Today is not monday');
   break;
case'tuesday':
   console.log('Yes, today is tuesday');
   break;
default:
console.log('Please enter a valid day');
}
//In this example, the code terminates after 2nd case, as the condition is satisfied at case 2//


Ternary Operator

It is a simple way of writing an If Else statement.

It takes three values or operands:

  • A condition
  • Expression to execute if the condition is true
  • Expression to execute if the condition is false

Let's understand this with an example.

JavaScript
 
let playFootball = true
playFootball
? console.log('you needs football boots to play on ground')
: console.log('i dont wanna play')


The ternary operator is useful when you need to make a simple decision based on a single condition. It can make your code more concise and easier to read, especially when used with short expressions.

Conclusion

This blog discusses various conditional statements in JavaScript, which allow the execution of different blocks of code based on certain conditions. This includes If, Else, Else If, Switch, and Ternary operators. If statements are used to check whether a condition is true, while Else statements execute when the If condition is false. Else If statements are used when multiple options need to be considered. Switch statements are an alternative to If Else statements and make the code more concise. Ternary operators are a simple way of writing If Else statements.

JavaScript Conditional operator

Published at DZone with permission of Shashank Sharma. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • 5 Layers of Prompt Injection Defense You Can Wire Into Any Node.js App
  • Boosting React.js Development Productivity With Google Code Assist
  • Why Angular Performance Problems Are Often Backend Problems

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook