Conditional statements in JavaScript



There are three types of conditional statements in JavaScript βˆ’

  • If statement βˆ’ The if statement is used to execute code inside the if block only if the specific condition is met.
  • If else statement βˆ’ The If….Else statement is used to check only two conditions and execute different codes for each of them.
  • If else if else statement βˆ’ The if…else if…else statement is used for checking more than two conditions.

Following is the code to implement conditional statements in JavaScript βˆ’

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Conditional statements in JavaScript</h1>
<input type="text" class="numInput" />
<button class="Btn">CHECK</button><br />
<div class="result"></div>
<h3>Click on the above button to see if the above number is divisible by 2,3 or both</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let numInputEle = document.querySelector(".numInput");
   BtnEle.addEventListener("click", () => {
      if (numInputEle.value % 2 === 0 && numInputEle.value % 3 === 0) {
         resEle.innerHTML = "The numbers is divisible by 2 and 3 both";
      } else if (numInputEle.value % 3 === 0) {
         resEle.innerHTML = "The number is divisbly by 3";
      } else if (numInputEle.value % 2 === 0) {
         resEle.innerHTML = "The numbers is divisible by 2";
      } else {
         resEle.innerHTML = "The numbers isn't divisible by 2 or 3";
      }
   });
</script>
</body>
</html>

Output

On entering a number and clicking on β€˜CHECK’ button βˆ’

Updated on: 2020-07-20T08:06:19+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements