0

How check a number whether even or odd using java script?

30th Jan 2017, 2:11 PM
shaheen
5 Respostas
+ 3
You can use the number 2 with the modulus operator % (YourNumberHere%2) then do a check to see if it returns 0 or 1. if it returns 0, then the number is even. if it returns 1, the number is odd when you have an even number you will get 0 var x = 10 var y=x%2 document.write(y) //writes 0. when you have an odd number you will get 1 var x = 23 var y=x%2 document.write(y) //writes 1.
30th Jan 2017, 2:34 PM
Mini
+ 2
Another option probably more efficient in case of intensive use, is to do a binary AND with one ( has behaviour to 'mask' all the not set to 1 bits, so get the value of the most right bit ) to have the same result as modulo two ( % 2 ) but without need to perform division ( as modulo ): var x=10; var y=x&1; document.write(y); // writes 0. x=23; y=x&1; document.write(y); // writes 1.
30th Jan 2017, 9:09 PM
visph
visph - avatar
+ 1
for this you use the %(modulo) operator, for example 4%2 will return 0. whenever this return 0 the number is even, everything else is odd!
30th Jan 2017, 2:44 PM
N1NJ4BR
0
divide by 2, if it returns a float fail as even
30th Jan 2017, 2:19 PM
Louis Milotte
Louis Milotte - avatar
0
var numToTest = 45; var result; if(numToTest%2===0){ result = "EVEN" } else{ result = "ODD" }
4th Mar 2020, 9:05 PM
J.Thrice
J.Thrice - avatar