What does % do? Help with understanding its use in "ES6: Write Higher Order Arrow Functions" hint

I understand what most of the code in line 5 is doing. The one part I’m not completely clear on is the part in the filter that is num % parseInt(num) ===0

I’m trying to filter out the decimals. At first I tries using num.isInteger and that didn’t work and I think the reason why is that the return value of that is a “true/false” and not a string or array of the numbers that are integers.

parseInt gives a string of numbers, which is good! So I understand why this should be used.

The “%” confuses me. I looked it up and it’s listed as “Modulus (division remainder)” so what is going on here? Am I dividing all my numbers by themselves and seeing if that gives me 0, and then taking that string further down the chain of functions? I don’t understand how that would get rid of the decimals and pass only whole numbers. Since all numbers divided by themselves are 1 I don’t see how that would pass.

I think I’m fundamentally misunderstanding the use and meaning of “%” here. Could anyone help clarify this?

1 Like

% is the modular function. It finds the remainder instead of the quotient value of a division expression.


var x;
x = 5 % 2; // x = 1
x = 6 % 2; // x = 0, it divides cleanly, so no remainder
x = 11 % 3; // x = 2; 3*3 = 9, 11-9 = 2 the remainder 

The filter function, in question, filters out values that are greater than 0 (num > 0) and are not decimals (num % parseInt(num) === 0). The remainder function in the case of the decimal values will evaluate somewhat like this:

5.6 % parseInt(5.6) === 0
5.6 % 5 === 0
0.6 === 0 

This should end up giving you a false since the remainder of the division is 0.6 and not 0.

Thank you for this explanation. Your example and explanation of x = 11 % 3 really helped me understand this. So with a decimal
5.6 % parseInt(5.6) ===0
parseInt turns 5.6 into 5
5 goes into 5.6 one time and then 0.6 remains. Obviously that is not equal to zero

I only wrote this reply to help solidify my understanding. I know that it really only repeats the same thing you said. But anyway… THANK YOU!

1 Like

this helped me thanks so much

@NarlaThotep, @whiteobah - just fyi, there are more obvious ways to do what this is doing:

  1. % 1. If you divide any integer by 1, there will be no remainder:
    5 % 1 // this is 0 
    5.6 % 1 // this will not be 0
    5 % 1 === 0 // this is true (it is an integer)
    5.6 % 1 === 0 // this is false (it's not an integer)
  2. Even clearer: Number.isInteger(number) is true if an integer, false if not.
    Number.isInteger(10) // this is true
    Number.isInteger(10.1) // this is false
1 Like

thanks… so much i understand better