×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

JavaScript | Example of if with else

JavaScript Example of if with else: In this tutorial, we will learn how if with else works in JavaScript? Here, we are writing a JavaScript example to demonstrate the use and working of if with else in JavaScript. By Pankaj Singh Last updated : July 30, 2023

JavaScript | if with else / if-else statement

In JavaScript, you can use an if-else statement to write a new block to execute if the given condition is false. The if-else statement has one condition and two blocks separated by if and else.

Consider the below syntax of if-else statement:

if (condition) {
  //  Block-True
} else {
  //  Block-False
}

If the given condition is true, then "Block-True" will be executed. If the condition is false, then "Block-False" will be executed.

JavaScript Example of if with else (if-else)

In this example, we are reading two integer values (through HTML) and finding the greatest/largest number among them.

Code (JS & HTML):

<!DOCTYPE html>

<HTML>
  <HEAD>
  
    <SCRIPT>
      function Find() {
        var a = parseInt(document.getElementById("txta").value);
        var b = parseInt(document.getElementById("txtb").value);
		
        var g = 0;
		
        if (a > b) {
          g = a;
        } else {
          g = b;
        }
		
        document.getElementById("txtc").value = "" + g;
      }
    </SCRIPT>
	
  </HEAD>
  
  <BODY>
    <h2>If with Else</h2>
    <hr />
    <table>
      <tr>
        <td>
          <label>Enter A:</label>
        </td>
        <td>
          <input type="text" name="txta" id="txta" />
        </td>
      </tr>
      <tr>
        <td>
          <label>Enter B:</label>
        </td>
        <td>
          <input type="text" name="txtb" id="txtb" />
        </td>
      </tr>
      <tr>
        <td>
          &nbsp;
        </td>
        <td>
          <input type="button" value="Find" onclick="Find()" />
        </td>
      </tr>
      <tr>
        <td>
          <label>Greater</label>
        </td>
        <td>
          <input type="text" name="txtc" id="txtc" readonly />
        </td>
      </tr>
    </table>
  </BODY>
  
</HTML>

Output

if with else example | js

JavaScript Examples »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.