Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Saw this in my newsletter. Tested on Chrome and Firefox. I still can't figured it out.

[]+(-~{}-~{}-~{}-~{})+(-~{}-~{});    //=>  "42"
like image 521
geckob Avatar asked Jun 11 '15 20:06

geckob


People also ask

What does return [] do in JavaScript?

The return statement ends function execution and specifies a value to be returned to the function caller.

What does '!' Mean in JavaScript?

The ! symbol is used to indicate whether the expression defined is false or not. For example, !( 5==4) would return true , since 5 is not equal to 4. The equivalent in English would be not .

How do you stop a return in JavaScript?

Using break to exit a function in javascript Break is mostly used to exit from loops but can also be used to exit from functions by using labels within the function.

What is $() in JavaScript?

$() The $() function is shorthand for the getElementByID method, which, as noted above, returns the ID of a specific element of an HTML DOM. It's frequently used for manipulating elements in a document. $() allows for shorter and more efficient JavaScript coding.


2 Answers

Evaluating:

~{}

is evaluated using the internal function:

~ToInt32({})

which gives -1.

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

Therefore, in this case

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

As you have []+ in the start of expression, javascript use plus operands like string. So you have "" + "4" + "2" = "42"

like image 162
user3272018 Avatar answered Sep 25 '22 19:09

user3272018


The ~ operator is a Bitwise NOT operator. It returns the "1's complement" of a number. Because of that {} is converted into a number, resulting in NaN. The same would happen with +{} == NaN. The bitwise not of ~NaN == -1. So:
(-~{}-~{}-~{}-~{}) == 4 & (-~{}-~{}) == 2

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

From that, the full parsing is: []+ /*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 validate this via typeof([]+(-~{}-~{}-~{}-~{})+(-~{}-~{})) === 'string'

like image 45
Amit Avatar answered Sep 23 '22 19:09

Amit