0

How can ich check if a number is un/even? JavaScript!!

I have the number 12 how can I check if this number is even / odd?

26th Dec 2016, 8:56 PM
TheSimonLP YT
TheSimonLP YT - avatar
4 Réponses
+ 2
var testNumber=34; if (testNumber%2==0){ alert("even number"); }else{ alert("odd number"); }
26th Dec 2016, 9:03 PM
seamiki
seamiki - avatar
+ 3
Another solution is to use binary operators ( and accessory using the ternary one for doing the conditional statement ) : alert( ( test_nb & 1 ) ? "odd" : "even" ); "And" ( & ) binary operator provide kind of masking, so ( n & 1 ) keep only the most right bit ( in binary representation ), so give same result as ( n % 2 ) but in a more efficient way...
27th Dec 2016, 7:19 AM
visph
visph - avatar
0
Yes the same thing I tested right now in this second but thank you!
26th Dec 2016, 9:06 PM
TheSimonLP YT
TheSimonLP YT - avatar
0
Use modulus: function even(n) { return n % 2 == 0; } function isodd(n) { return n % 2 != 0; } isodd(15) //true even(10) //true
26th Dec 2016, 9:07 PM
Mofid
Mofid - avatar