0

What does !+ (exclamation mark addition) mean in JavaScript?

Why is !+"000" true?
Why is !+"0010" false?

Tries:

!+"000" // true
!+"00010" // false
!+"0a0" // true
!+"0,0" // true
!+[0,0,0] // true
!+[0,1,0] // true
true+"000" // true000

I've tried to search:

Here I saw the code: JS - Check if string contain only 0

This information is hard to find on the Internet.

David Lukas
  • 1,184
  • 2
  • 8
  • 21
  • 1
    It's two separate unary operators – Bergi Dec 13 '21 at 16:09
  • 1
    See [What does this symbol mean in JavaScript?](/q/9549780/4642212) and the documentation on MDN about [expressions and operators](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators) and [statements](//developer.mozilla.org/docs/Web/JavaScript/Reference/Statements). Operators can be combined. You wouldn’t ask about every possible combination, right? – Sebastian Simon Dec 13 '21 at 16:11
  • 1
    `true + "000"` doesn’t use the unary `+`, but the binary one. The [specification](//tc39.es/ecma262/#sec-applystringornumericbinaryoperator) explains in detail what it does. – Sebastian Simon Dec 13 '21 at 16:15

1 Answers1

2

+ is unary plus. It'll convert the expression that follows to a number.

Then, ! negates the expression that follows: if it's truthy, the result is false. If it's falsey, the result is true.

A couple of examples:

!+"000"
!0 // because '000', when converted to a number, is 0
true

!+"00010"
!10 // because "00010", when converted to a number, is 10
false // because 10 is truthy

!+[0,1,0]
!NaN // because arrays can't be converted to numbers directly (usually)
true
luk2302
  • 55,258
  • 23
  • 97
  • 137
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320