Understanding weirdness of the “!” bang operator in JavaScript

There are some things we don’t know about how the ! operator works in Javascript.


Basics

The ! is a logical operator that will convert a value to its opposite boolean. Since JavaScript will coerce values, it will “convert” a value to its truthy/falsey form and return the opposite boolean value.

When we perform the ! operation on a number other than 0 it, returns false. This is because all numbers other than 0 are truthy.

// evaluates to false
!1
!-10
!1.2

The ! operation on 0, null, undefined, NaN returns true since they are falsey.

//evaluates to true
!0
!NaN
!null
!undefined

If we perform ! on undefined variables then it returns true.

var a ;
!a // true

Similarly, if we perform ! on a variable which has some value or points to some a reference then it returns false.

var a = [];
!a; // false

The weird part

When we do:

! + [] // then it is evaluated to true 

The reason is, the + operator only works on strings and numbers, so if we perform a binary operation on an array, then the array is converted to a string. So the detailed view is:

! + [] 
is converted internally into
! + String([])
! + "" //it evaluates true because ! on empty string returns true

So now let’s try another large problem (which I found on Twitter, the solution also available there 😃)

(! + [] + [] + [] + ![]) 
! + [] --> true 
true + [] --> "true"
"true" +[] --> "true"
"true" + ![] -- >"truefalse"

If you want to learn more about these concepts, you should study JavaScript type coercion and how truthy/falsey values work in JS.


If you find this helpful surprise 🎁 me here.

Share if you feel happy.

Follow Javascript Jeep🚙 if you feel worthy.


https://gitconnected.com/learn/javascript

Leave a comment

Design a site like this with WordPress.com
Get started