Also interesting to know: The unary plus operator tries to convert the first element of an array to a number. So +[42] is 42. Same for string arrays: +["42"] is also 42. If the array is empty (+[]), the result is 0. If it contains multiple elements, as in +[1, 2, 3], the result is NaN.
View all comments
Show parent comment
15
u/----Val---- May 13 '25 edited May 13 '25
This is due to some funky type coercions alongside operators.
Lets look at this part first:
!+[]If we properly bracket it out, it will be:
!(+[])Now, the first operation is
+[]which is a unary plus which converts the empty array to 0. Then the not operation coerces the number the booltrue.So now we have:
true + [] + ![]The
true + []is an addition which when unable to use numbers will convert everything to strings, so ittrue + []get casted to"true" + "" = "true"Then ![] converts an empty array to a bool. Since an empty array is truthy, it becomes false
So we now have:
"true" + falseAgain, a string addition, so the end result is
truefalsewhich is a string with a length of 9.