Logical differences between very similar terms in beginner javascript

What is the difference between these two terms:

if(counter % 4 != 0) if(counter % 4 == !0) 

I do not see any logical difference, but my computer (and I am 100% sure that my computer is more logical than me).

All understanding was appreciated.

+4
source share
3 answers

The operator ! (not) in JavaScript performs type coercion - it tries to convert the value to a Boolean value (true or false). 0 in JavaScript is false, therefore! 0 is the opposite of false, i.e. true.

So your first if remains the same:

 if(counter % 4 != 0) 

but the second one is actually

  if(counter % 4 == true) 

which definitely doesn't match.

Edit:

JavaScript also causes coercion when using non-strict operators != And == (compared to strict !== and === ), so in this case, if counter % 4 becomes 1, it will evaluate to true , since 1 is true value.

Here is a list of false values ​​in JavaScript: http://www.sitepoint.com/javascript-truthy-falsy/

+6
source

This might make sense if you try to read your code as text:

  • Is counter % 4 the same as not 0 ?

not 0 , or !0 , gives true in Javascript, so this will be:

  • Is counter % 4 the same as true ?

The result of the instruction depends on the value of counter . See the Google Chrome Javascript Console for more details:

enter image description here

+1
source

! 0 is 1, so your conditional view looks like this:

 if(counter % 4 != 0) if(counter % 4 == 1) 
-2
source

All Articles