JavaScript: Why [] + (- ~ {} - ~ {} - ~ {} - ~ {}) + (- ~ {} - ~ {}); returns "42"

I saw this in my newsletter. Tested in Chrome and Firefox. I still can not understand.

[]+(-~{}-~{}-~{}-~{})+(-~{}-~{}); //=> "42" 
+6
source share
2 answers

Rating:

 ~{} 

evaluated using an internal function:

 ~ToInt32({}) 

which gives -1.

Ref ECMA spec - http://www.ecma-international.org/ecma-262/5.1/#sec-9.5 and this explanation is http://jibbering.com/faq/notes/type-conversion/#tcToInt32

Therefore, in this case

 (-~{}-~{}) == 2 (-~{}-~{}-~{}-~{}) == 4 

Since you have []+ at the beginning of the expression, javascript uses plus operands of type string. So you have "" + "4" + "2" = "42"

+6
source

The ~ operator is a bitwise NOT operator. It returns the "1 complement" of the number. Because of this, {} converted to a number, which leads to NaN . The same thing will happen with +{} == NaN . The bit value is not ~NaN == -1 . So:
(-~{}-~{}-~{}-~{}) == 4 and (-~{}-~{}) == 2

DefaultValue for an empty array is an empty string. For example []==[]+[] && []+[]==''

Hence the full analysis: []+ /*converted to ''+*/ (-~{}-~{}-~{}-~{}) /*Equals numeric 4, but concatenated as a string to become '4'*/ + (-~{}-~{}) /*Equals numeric 2, but concatenated as a string to become '2'*/ , and the end result is actually '42' .

You can check this via typeof([]+(-~{}-~{}-~{}-~{})+(-~{}-~{})) === 'string'

+3
source

Source: https://habr.com/ru/post/988954/


All Articles