3

By what logic js works (!+[]+[]+![]).length returns 9? How is that possible? As I know js has dynamic types cast but very hard to understand whats going on here

console.log((!+[]+[]+![]).length);
Isaac
  • 12,042
  • 16
  • 52
  • 116
rebilliony
  • 177
  • 10

2 Answers2

5

First: +[]

+[] is casting the array to a string, then a number. [] becomes "" and then becomes 0. +[123] is +"123", so it's 123 +[1,2] is +"1,2", this is not a number, so it's NaN

!+[] is !0 (not zero), so it's the boolean true

Second: true + []

Convert both to string, so "true" + "" is "true"

Third: ![]

![] is the boolean false, because an object/array is always thruty.

Fourth: "true" + false

Convert boolean false to a string, so "true" + "false" is "truefalse"

"truefalse".length is 9

progysm
  • 1,072
  • 6
  • 7
3

First we have to understand !+[]+[]+![]:

!+[] = !0 = true   
true+[] = "true"
![] = false
"true"+false = "truefalse"

so length of !+[]+[]+![] is length of "truefalse" so it's 9

Firemen26
  • 1,025
  • 12
  • 21