Saw this in my newsletter. Tested on Chrome and Firefox. I still can't figured it out.
[]+(-~{}-~{}-~{}-~{})+(-~{}-~{}); //=> "42"
The return statement ends function execution and specifies a value to be returned to the function caller.
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 .
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.
$() 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.
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"
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With