Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning `{} + []` to a variable

>> {} + []
0

So EmptyObject + EmptyArray evaluates to 0. (Disclaimer: I don't fully understand why this is.) Okay, now I want to assign this 0 to a variable! Seems pretty easy:

>> var a = {} + [];
undefined
>> a
"[object Object]"

Well, maybe not so easy. Googles a bit... Aha! {} in this context is actually a code block, not an empty object. So lemme make it look more like a code block:

>> var a = 
   {

   }
   + [];
undefined
>> a
"[object Object]"

...dang. Note to self: JavaScript ignores whitespace.


Is there any way I can assign {} + [] (or similar) to a variable, but still have that {} + [] evaluate to 0?

like image 961
The Guy with The Hat Avatar asked Mar 31 '14 18:03

The Guy with The Hat


People also ask

How do you assign a value to a variable write an example?

The = symbol is known as the assignment operator. It is also possible to declare a variable and assign it a value in the same line, so instead of int i and then i = 9 you can write int i = 9 all in one go. If you have more than one variable of the same type you can also declare them together e.g.

How do you assign a value to a variable in HTML?

Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.

How do you assign a value to a variable in R?

Use variable <- value to assign a value to a variable in order to record it in memory. Objects are created on demand whenever a value is assigned to them. The function dim gives the dimensions of a data frame. Use object[x, y] to select a single element from a data frame.


1 Answers

No, there is no way to assign that exact code to a variable and have it work out to 0, because the parsing of that code that gives 0 does not constitute an expression†, and only expressions can be assigned. The reason you're getting that 0 is because the braces are being essentially ignored as an empty statement and then you're getting the result of the expression + [] (that is, the unary + operator applied to an empty array). So in order to get the same result out, you'd need to alter the expression so that it just worked out to +[]. For example, you could do var a = ({}, + []) and that would give you the right answer (because the comma causes + [] to be evaluated separately).

† This is also the reason it gives a different answer when you try to assign it. That forces the code to be parsed as an expression, so the {} is no longer an empty block and the + is no longer the unary +, but instead it's the binary plus with an empty object and an empty array as operands.

like image 77
Chuck Avatar answered Oct 11 '22 03:10

Chuck