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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack

Trending

  • Cloud Security and Privacy: Best Practices to Mitigate the Risks
  • Agile’s Quarter-Century Crisis
  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • Beyond Simple Responses: Building Truly Conversational LLM Chatbots
  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.2K 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

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!