Unlock the Power of Conditional Statements in JavaScript

The if…else Statement: A Simple Calculator Example

Imagine building a simple calculator that takes in an operator (+, -, *, /) and two numbers as input. Using the if…else statement, we can create a program that performs the corresponding operation based on the user’s input.


const operator = prompt("Enter an operator (+, -, *, /): ");
const num1 = parseFloat(prompt("Enter the first number: "));
const num2 = parseFloat(prompt("Enter the second number: "));

if (operator === "+") {
  const result = num1 + num2;
  console.log(`The result is: ${result}`);
} else if (operator === "-") {
  const result = num1 - num2;
  console.log(`The result is: ${result}`);
} else if (operator === "*") {
  const result = num1 * num2;
  console.log(`The result is: ${result}`);
} else if (operator === "/") {
  if (num2!== 0) {
    const result = num1 / num2;
    console.log(`The result is: ${result}`);
  } else {
    console.log("Error: Division by zero is not allowed.");
  }
} else {
  console.log("Error: Invalid operator.");
}

The switch…case Statement: An Alternative Approach

But what if we want to simplify our code and make it more efficient? That’s where the switch…case statement comes in. In this example, we’ll create a similar calculator program using switch…case.


const operator = prompt("Enter an operator (+, -, *, /): ");
const num1 = parseFloat(prompt("Enter the first number: "));
const num2 = parseFloat(prompt("Enter the second number: "));

switch (operator) {
  case "+":
    const result = num1 + num2;
    console.log(`The result is: ${result}`);
    break;
  case "-":
    const result = num1 - num2;
    console.log(`The result is: ${result}`);
    break;
  case "*":
    const result = num1 * num2;
    console.log(`The result is: ${result}`);
    break;
  case "/":
    if (num2!== 0) {
      const result = num1 / num2;
      console.log(`The result is: ${result}`);
    } else {
      console.log("Error: Division by zero is not allowed.");
    }
    break;
  default:
    console.log("Error: Invalid operator.");
}

Taking Your JavaScript Skills to the Next Level

Mastering conditional statements is just the beginning. With practice and patience, you can create complex programs that interact with users, manipulate data, and produce dynamic outputs.

Remember, the key to mastering JavaScript is to keep practicing and pushing yourself to try new things. With dedication and persistence, you can become a proficient JavaScript developer and create amazing applications that interact with users in meaningful ways.

Leave a Reply