I've seen a explanation for something similar to b = !b. But I'm not understanding it well enough to translate over to this usage.
What does
var a = !1;
do?
I've seen a explanation for something similar to b = !b. But I'm not understanding it well enough to translate over to this usage.
What does
var a = !1;
do?
a = !1
is a shorthand way of writing a = false
. This is normally used when trying to compress (minify) JavaScript because it saves three bytes.
If you're seeing this in ordinary un-minified JS, then someone is probably being either lazy or obfuscatory.
Run this in chrome dev tools and see what you get.
a evaluates to false because 1 is a truthy value in javascript and therefore negating it produces false
Maybe read this http://james.padolsey.com/javascript/truthy-falsey/ . It's quite interesting :)
In general the !
will invert the boolean value of its operand.
So !a
will be true
if a
is false
or it will be false
if a
is true
.
Hope that helps :)
!
is a not
operator. Therefore ! true
is equal to false
. It's result will be either true
or false
All values in JavaScript are either "truthy" or "falsy". This describes their interpretation in contexts where a boolean
(true
or false
) is expected.
Examples of "truthy" values: true, 1, [], {}, "text"
Examples of "falsy" values: false, 0, ""
!1
is a negation of a truthy value, which will evalute to false. b = !b
is a toggler
, it will change the value from a truthy
to a falsy
, and vice versa.
The !
operator is known as the Logical NOT operator.
In short, it returns false
if the following value is 'truthy', and true
otherwise.
Since 1
is 'truthy', your example, !1
reads NOT 1
, which will return false
.