2

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?

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
Evan Ward
  • 1,371
  • 2
  • 11
  • 23
  • It means that `a` is `false`, and it's pretty useless. Maybe the `1` is being output from the server side? Then it could make some sense. – bfavaretto Aug 06 '13 at 00:32
  • 2
    @bfavaretto 3 bytes saved. Heroic. – Wesley Murch Aug 06 '13 at 00:33
  • Thanks, I've been trying to dissect code to try and get a better understanding of different programming methods and i've been seeing a lot of snippets that have turned out to be convoluted ways of doing simple things. – Evan Ward Aug 06 '13 at 00:34
  • `!` is a logical NOT (`!!` is a negation operator), so if you put `!` in front of a value, it will get "negated" to it's opposite boolean value. `!true == false`, `!!true == true`, `!false == true`, etc. `1` evaluates as boolean `true`, so `!1 == false`. It's more useful when you need a boolean value of some non-boolean expression. – Jared Farrish Aug 06 '13 at 00:35

5 Answers5

6

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.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
1

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 :)

Connor Atherton
  • 161
  • 3
  • 11
0

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 :)

woofmeow
  • 2,370
  • 16
  • 13
0

! 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.

sabof
  • 8,062
  • 4
  • 28
  • 52
0

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.

Carl Groner
  • 4,149
  • 1
  • 19
  • 20