×

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 focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

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 comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

Javascript Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 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 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 Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.

Javascript Tutorial

JavaScript is a light-weight, dynamic scripting language that is mainly employed to create interactive front-end web applications. It was originally developed in 1995 by Brendan Eich at Netscape Communications Corporation...

5 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.

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.

Javascript Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute read.

Javascript Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

2 minutes read.

Javascript Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 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 Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 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.