Skip to content

JavaScript division operator (/)

  • by

The JavaScript division operator (/) is used to perform floating-point division between two numbers. It is important to handle the case where the second operand is zero, as division by zero is undefined and will result in an error.

x / y
// OR
dividend / divisor

Here, dividend is the number that will be divided by the divisor, and / is the division operator. The result of the division is the quotient of the two numbers.

The division operator (/) calculates the quotient of its operands, where the number on the left side of the operator is the dividend, and the number on the right side is the divisor.

JavaScript division operator example

A simple example of code divides 10 by 2 using the division operator.

let dividend = 10;
let divisor = 2;
let quotient = dividend / divisor;
console.log(quotient); // Output: 5

In JavaScript, dividing a number by zero using the division operator (/) will result in the value Infinity or -Infinity.

To handle the error that occurs when dividing a number by zero using the division operator (/) in JavaScript, you can use conditional statements to check if the divisor is zero before performing the division operation.

<!DOCTYPE html>
<html>
  <body>
    <script>
    let num = 10;
    let zero = 0;
    let result;

    if (zero === 0) {
        console.log("Error: Division by zero is not allowed.");
    } else {
        result = num / zero;
        console.log(result);
    }

    </script>
  </body>
</html>

Output:

JavaScript division operator

Alternatively, you can use a try-catch block to handle the error that occurs when dividing a number by zero.

let num = 10;
let zero = 0;
let result;

try {
  result = num / zero;
  console.log(result);
} catch (error) {
  console.log("Error: " + error.message);
}

Comment if you have any doubts or suggestions on this JS Operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *