Home  >  Article  >  Web Front-end  >  What is the Purpose of the % Operator in JavaScript, and How is it Used?

What is the Purpose of the % Operator in JavaScript, and How is it Used?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-22 11:06:02979browse

What is the Purpose of the % Operator in JavaScript, and How is it Used?

The % Operator in JavaScript

JavaScript's % operator performs the modulus operation. It calculates the remainder when one number is divided by another and returns the result. This operator is used to check if a number is divisible by another without having to use floating-point division.

Operation:

The modulus operator is used as follows:

<code class="javascript">var1 % var2</code>

Where:

  • var1 is the dividend
  • var2 is the divisor

Example:

<code class="javascript">console.log(12 % 5); // 2
console.log(-1 % 2); // -1</code>

Usage Cases:

The % operator has various applications, including:

  • Checking if a number is even or odd (the remainder of a number by 2 indicates if it's even or odd)
  • Finding the last digit of a number (the remainder of a number by 10 gives the last digit)
  • Calculating the position of an element within an array (the remainder of the index by the array length gives the position)

The above is the detailed content of What is the Purpose of the % Operator in JavaScript, and How is it Used?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn