9

When simplifying my code, a stack overflow user changed this line of code:

if (place > sequence.length -1) {
    place = 0;

to this:

 place = place % sequence.length;

and I'm wondering what this line actually does and how you would define the use of this line and the use of the percentage sign. Thanks for help in advance.

AntsOfTheSky
  • 195
  • 2
  • 3
  • 17
  • take a look at [this](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators) – m87 Feb 25 '17 at 21:01
  • Better here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder – Michel Moraes Aug 29 '20 at 12:01

3 Answers3

9

(%) is the modulus operator, it will let you have the remainder of place/sequence.length.

5 % 1 = 0 // because 1 divides 5 (or any other number perfectly)
10 % 3 = 1 // Attempting to divide 10 by 3 would leave remainder as 1
Amresh Venugopal
  • 9,299
  • 5
  • 38
  • 52
1

The % symbol is used in most programming languages, including JavaScript, as Modulu.

modulo is the operation use to find the remainder after division of one number by another.

For example:

7 % 3 = 1

10 % 2 = 0

9 % 5 = 4

DMEM
  • 1,573
  • 8
  • 25
  • 43
0

It is the remainder operator %, not the modulo operator, which Javascript actually does not have.

Remainder (%)

The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of ECMAScript, the difference being that the modulo operator result would take the sign of the divisor, not the dividend.

console.log(-4 & 3);
console.log(-3 & 3);
console.log(-2 & 3);
console.log(-1 & 3);
console.log(0 & 3);
console.log(1 & 3);
console.log(2 & 3);
console.log(3 & 3);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 2
    Where strict definitions are concerned, I find it better to quote [*ECMA-262*](http://ecma-international.org/ecma-262/7.0/index.html#sec-applying-the-mod-operator): "*The % MultiplicativeOperator yields the remainder of its operands from an implied division; the left operand is the dividend and the right operand is the divisor...The result of a floating-point remainder operation as computed by the % operator is not the same as the “remainder” operation defined by IEEE 754-2008.*" so it's not, strictly, a "remainder operator" either. ;-) – RobG Feb 25 '17 at 21:44