Home » Articles » Javascript fun

Javascript fun

Thu Feb 16, 2017

Javascript is a fun language that allows you to write crazy AND valid code.

Keep in mind that adding [] converts the expression to a String, for example:

[] + [] === ""

Getting true and false is easy, preceding something with ! converts it to Boolean (in our case, false), and negating the whole construct again gives us true.

![] === false
!![] === true

Using the same way of thinking, preceding with + converts to Number.

+[] === 0
+!+[] === 1

Let’s do some math.

+!+[] + +!+[] === 2
+[+!+[] + [+!+[]]] === 11
+[+!+[] + +!+[] + +!+[] + [+!+[]]] === 31

A string can be used as an array of characters by using this notation:

"this is a string"[0] === "t"

NaN is easy to get too.

+[![]] === NaN
{} + {} === NaN

Also, making multiple digits is simple if we’re concatenating multiple strings, then convert it to a number:

+("1" + "2") === 12

Now we can combine stuff and get the letter a:

![] === false
![] + [] === "false"
+!![] === 1
------------------------
(![] + [])[+!![]] === "a"  // the same result as "false"[1]

There are cool ways to get all the letters of the alphabet.

Now, what will be the result of the expressions below:

{} + []
[] + {}
{} + [] === [] + {}
+{} + []
+{} + +[]
[][[]]
[][[]] + []
[][[]] == [][[]] + []
[][[]] === [][[]] + []

Javascript is fun, isn’t it?


Next: »