How to use Modulus Operator in Javascript

Description

The modulus (remainder) operator is represented by a percent sign %.

If either of the operands isn't a number, it is converted to a number behind the scenes using the Number() casting function. This means that an empty string is treated as 0, and the Boolean value of true is treated as 1.

The modulus operator behaves differently for special values, as follows:

  • If the operands are numbers, regular arithmetic division is performed.
  • If the dividend is an infinite number and the divisor is a finite number, the result is NaN.
  • If the dividend is a finite number and the divisor is 0, the result is NaN.
  • If Infinity is divided by Infinity, the result is NaN.
  • If the dividend is a finite number and the divisor is an infinite number, then the result is the dividend.
  • If the dividend is zero and the divisor is nonzero, the result is zero.
  • If either operand isn't a number, it is converted to a number behind the scenes using Number().

Example


var result = 26 % 5;    //equal to 1
console.log(result);

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions