>> {} + [] 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
?
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.
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.
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.
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.
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