×

Javascript If Else

Introduction

The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else, it is simple to create a condition so that, if tested as true, it causes one section of the code to execute and a false test causes an alternative section to execute. This makes the code responsive to a wide range of situations. The if-else statement can also be extended with else-if blocks to respond to multiple conditions. If-else statements are required for creating responsive and smart programs that respond differently based on some conditions or user inputs.

Syntax:

if (condition) {

  // Code to be executed if the condition is true

} else {

  // Code to be executed if the condition is false

}
JavaScript If Else

Importance of if else statement in JavaScript

The importance of if-else statements in JavaScript cannot be overstated since it makes conditional decision-making in code possible. The if-else statements enable developers to create responsive and dynamic programs by executing particular code segments based on different conditions.

Whether it is about managing user inputs, error checking, or creating branching logic, if-else statements give programmers the functionality needed to create flexible and dynamic software. They are required in creating features like login authentication, data validation, and user interactions.

The if-else statements in JavaScript are basic building blocks for creating robust and smart programs that can respond accordingly to a wide range of situations, making them an integral part of contemporary web development and programming.

Flow Chart of if-else

The below flow chart demonstrates how the if-else statement works.

JavaScript If Else

JavaScript supports the following forms of if...else statement −

  • if statement
  • if...else statement
  • if...else if... statement.

JavaScript If-Statement

The if-statement is a method for determining whether something should occur based on a certain condition. If the condition holds, the block of statements will execute; otherwise, they won't execute.

Syntax:

if(condition)

{

// Statements to execute if

// the condition is true

}

The if-statement examines true or false values; if the value is true, the statements in the block will execute. If curly braces '{' and '}' are not used after if(condition), the if-statement will use the next statement as its block by default. For instance,

if(condition)
   statement1;
   statement2;
// Here if the condition is true, if block
// will consider only statement1 to be inside
// its block.

Flow chart

JavaScript If Else

Code

<html>

<body>    

   <div id ='output'> </div>

   <script type = "text/javascript">

      let result;

      let age = 20;

      if( age > 18 ) {

         result = "Welcome back";

      }

              document.getElementById("output").innerHTML = result;

   </script>     

<p> Let’s begin the tutorial </p>

</body>

</html>

Output

JavaScript If Else

JavaScript if-else statement

JavaScript's if-else statement plays a vital role in deciding what code to execute based on certain conditions. The if statement is used to indicate that a certain block of code will be executed if a certain condition is satisfied. If the condition is not satisfied, then that block won't be executed. To run code when something else needs to be done if the condition is not satisfied, we use the else statement. By using the else statement combined with the if statement, you can define an alternative block of code to be executed when the first condition is not fulfilled.

Syntax:

if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}

The JavaScript expression is evaluated. If it is true, the code in the 'if' block is run. If the expression is false, the code in the 'else' block is run.

Flow chart:

JavaScript If Else

Code

<html>

<body>

   <div id ='output'> </div>

   <script type = "text/javascript">

              let result;

      let age = 15;

      if( age > 18 ) {

         result = "Hello All";

      } else {

         result = "Welcome back";

      }

      document.getElementById("output").innerHTML = result;

   </script>    

   <p> Let's begin the tutorial </p>

</body>

</html>

Output

JavaScript If Else

Code 2

let year = 2025;

if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {

  console.log(`${year} is a leap year.`);

} else {

  console.log(`${year} is not a leap year.`);

}

Output

JavaScript If Else

The provided JavaScript code verifies whether the variable 'year' is a leap year or not. This is done by first verifying whether 'year' is divisible by 4 but not by 100 (i.e., not a multiple of 100) or, alternatively, whether it is divisible by 400. If either of these is a true statement, the program outputs that 'year' is indeed a leap year; otherwise, it says 'year' is not a leap year.

Code 3

let number = 13;

if (number % 2 === 0) {

  console.log(`${number} is even.`);

} else {

  console.log(`${number} is odd.`);

}

Output

JavaScript If Else

This JS script determines whether the variable "number" is even or odd. It applies the modulo operator (%) to determine what the remainder is when "number" is divided by 2. If the remainder is 0, it will output that the number is even; otherwise, it will output that the number is odd. In this instance, the output will be "13 is odd."

JavaScript nested-if statement

JavaScript permits you to nest if statements within other if statements, thereby making nested if statements possible. A nested if is an if statement that is the target of an if or else statement.

Syntax:

if (condition1)
{
   // Executes when condition1 is true
   if (condition2)
   {
      // Executes when condition2 is true
   }
}

The above form is flexible and can be changed based on what you need when writing code for real-life applications. It can have or lack else statements and can have multiple if statements, up to any level, which can be nested in if or else statements.

Flow chart:

JavaScript If Else

Code

// JavaScript program to illustrate nested-if statement

let i = 10;


if (i == 10) {  // First if statement

    if (i < 15) {

        console.log("i is smaller than 15");

        // Nested - if statement

        // Will only be executed if statement above

        // it is true

        if (i < 12)

            console.log("i is smaller than 12 too");

        else

            console.log("i is greater than 15");

    }

}

Output

JavaScript If Else

JavaScript if-else-if ladder statement

The if-else-if ladder structure of JavaScript enables a user to choose from different possibilities. The if statements are tested one by one in top-to-bottom order. When a condition is met, the respective statement runs and the rest are skipped. If all conditions are not fulfilled, the last else statement runs.

Syntax:

if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;

This code is not special in any way. It is just a collection of if statements, where each if statement is a part of the else clause of the previous statement. The statements run based on which conditions are fulfilled; if none are fulfilled, the else block will run.

Flow chart:

JavaScript If Else

Code

<html>

<body>

   <div id ="demo"></div>

   <script type="text/javascript">

              const output = document.getElementById("demo")

      let language = "Java";

      if (language == "Java") {

         output.innerHTML="<b>Java language</b>";

      } else if (language == "C") {

         output.innerHTML="<b>C language</b>";

      } else if (language == "HTML") {

         output.innerHTML="<b>HTML langauge</b>";

      } else {

         output.innerHTML="<b>Unknown language</b>";

      }

    </script>

    <p> Chose the correct language </p>

</body>

<html>

Output

JavaScript If Else

Conclusion

If-else statements are a great addition to making decision-making processes flexible in your code. By checking for conditions and running different paths of code, these statements allow your programs to react to different scenarios. Knowing when and how to use if-else statements is important to making effective, responsive, and efficient JavaScript applications, and as such, they form a fundamental part of modern web development.


Related Topics

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

Javascript Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes read.

Javascript Print

JavaScript help's the functionality using the print function of window object. In JavaScript print function window.print() print the current web page when it executed. We can call function directly using onclick...

1 minute read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

Javascript Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

9 minutes read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

JavaScript Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 minutes read.

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

5 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

Javascript If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

6 minutes read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 minutes read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.