So I know this question seems kind of stupid, but recently I was going through some JS questions and I happen to do 1 % 2
in the browser console and I got 1
, while when I did 1 divided by 2 on a paper I got the reminder 0
. I am well aware of the concept that the value returned is the reminder, but why is it different in JavaScript and when I do on a paper ? Is there any underlying concept of JS that I'm not aware about ?
So in case of the MODULUS Operator(%
) if the first number is smaller than the second number then it returns the first number itself.
Here is an interactive snippet to test it out!
const n1 = document.getElementById("n1");
const n2 = document.getElementById("n2");
const result = document.getElementById("result");
function modulus() {
result.innerText = Number(Number(n1.value) % Number(n2.value));
}
function division() {
result.innerText = Number(Number(n1.value) / Number(n2.value));
}
<input type="number" placeholder="First Number" id="n1">
<br>
<br>
<input type="number" placeholder="Second Number" id="n2">
<br>
<br>
<button onclick="modulus()">Modules(%)</button>
<br>
<br>
<button onclick="division()">Division(/)</button>
<br>
<br>
<b>Result</b>
<br>
<span id="result"></span>