Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why console.log((!+[]+[]+![]).length) gives 9? [duplicate]

Tags:

javascript

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);
like image 640
rebilliony Avatar asked Dec 19 '25 12:12

rebilliony


2 Answers

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

like image 50
progysm Avatar answered Dec 22 '25 02:12

progysm


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

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

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

like image 24
Firemen26 Avatar answered Dec 22 '25 02:12

Firemen26



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!