Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this expression evaluated to "a" in JavaScript? [duplicate]

I got hold of some obfuscated JavaScript code. I tried to understand it, and doing this, I typed pieces of it in the console. I can't understand why

> ((!!+[]+"")[+!![]])
< "a"

Why is ((!!+[]+"")[+!![]]) equal to "a" in JavaScript? Is there some other code snippets to get others letters?

I guess it's something to do with automatic casting.

like image 863
WayToDoor Avatar asked May 28 '17 15:05

WayToDoor


People also ask

What is the use of Eval() in JavaScript?

The eval () is a function property of the global object in JavaScript. The eval () function accepts a string as an argument, evaluates it as an expression, and returns the result. string: It takes a string which is a JavaScript expression, variable, statement, or sequence of statements.

How to safely evaluate expressions in JavaScript?

Safely evaluate expressions in JavaScript in a simple yet powerful way, by using a Parsing Expression Grammar Recently, in a front-end project I was working on, the client needed to be able to define calculations by entering formulas using numbers, variables, and functions. The problem: how can you validate and (safely) evaluate such expressions?

Is there a JavaScript library for evaluating mathematical expressions?

It can also be made to use those Big Number libraries for arithmetic in case you are dealing with numbers with arbitrary precision. I went looking for JavaScript libraries for evaluating mathematical expressions, and found these two promising candidates: JavaScript Expression Evaluator: Smaller and hopefully more light-weight.

What is an expression in JavaScript?

In JavaScript, an expression is simply a way of asking a question that gets answered with a value — and always a single value. This is an expression: Here’s what’s happening above: You ask: “JavaScript, what is 5 + 5?” JavaScript: “5 + 5 evaluates to 10”.


2 Answers

( ( !!+[] + "" ) [ +!![] ] )
( (  !!0  + "" ) [ +true ] )
( ( false + "" ) [ +true ] )
( (   "false"  ) [   1   ] )
(         "false"[1]       )
(            "a"           ) 

Is there some other code snippets to get others letters ?

You can play with the same concept to get all the letters from "true", "false", "undefined", "NaN"...

like image 101
pomber Avatar answered Sep 20 '22 11:09

pomber


You should work on operator precedence and type castings in JavaScript:

!!+[] // Is falsey. this is same for !!+0 or !!+""
false + "" // Is "false". as 5+"" is "5".

![] // Is falsey.
!false // Is true
+true //  Is equal to 1. +[] = 0, +false = 0

And at least,

"false"[1] // Is "a"
like image 45
marmeladze Avatar answered Sep 22 '22 11:09

marmeladze