Remainder in JavaScript

Remainder in JavaScript
0

#1

Hello there
Can anybody explain what remainder % is and where do we use them in java script?
Thanks

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript


#2

Which step in the example do you not understand?

5 % 2 = 1 because
Math.floor(5 / 2) = 2 (Quotient)
2 * 2 = 4
5 - 4 = 1 (Remainder)

#3

are you asking what does the word ‘remainder’ mean?
This a mathematics concept and not related to coding.

The remainder is the amount left when you divide two numbers together.
so 5 divided by 5 has zero remainder
but 5 divided by 4 has one remainder


#4

Thanks for your reply ,trying to figure out how it works, give me some time to understand new to coding and did maths long time ago.


#5

if your maths is not very good, I would strongly suggest reviewing grade school maths first before learning to code in javascript or any other language.
www.khanacademy.org is a good website (free) for learning grade school maths.
you can try some tests from different grade to see how much you remember.


#6

Ok , i will have a look now.Thank you


#7

So in remainder numbers left after division have to be even and odd,but not decimal number.
e.g 5/2=2.5 but we take 2 as a remainder?


#8

remainder is never a decimal

5 divided by 2 gives a remainder of 1

here are five letters:
W W W W W

if you divide by 2 you split the letters like this
WW WW W

so only one W left without a second one therefore remainder is 1


#9

hmm . i understand now ,thank you.


#10

It’s used to check what the integer remainder is when you try to divide one number by another.

If I divide 11 by 4:

11 - 4 is 7 (divides once)
7 - 4 is 3 (divides twice)
For it to divide further, I have to end up with 0, not a negative number.
3 - 4 is negative, so I can’t divide more than two times, remainder is 3.

A common use is to see if a number is even. If the number is even, there will be no remainder after dividing by 2.

> 10 % 2
0

So 10 - 2 is 8. 8 - 2 is 6. 6 - 2 is 4. 4 - 2 is 2. 2 - 2 is 0, it divides cleanly, remainder is 0.

> 11 % 2
1

So 11 - 2 is 9. 9 - 2 is 7. 7 - 2 is 5. 5 - 2 is 3. 3 - 2 is 1. Can’t subtract further, so remainder is 1.

So if I make a function:

function isEven(number) {
  return number % 2 === 0
}

That’s saying “given a number, if I divide it by 2 and the remainder is 0, return true (it is even), but if the remainder is not 0, return false (number is not even)”


#11

Really helpful, thanks