According to the ECMA-262 Specification, the following statements return 1:
eval("1;;;;;")
eval("1;{}")
eval("1;var a;")
Ensuring that:
The value of a StatementList is the value of the last value producing Statement in the StatementList.
Can you explain these different returns ?
eval("{}") // undefined
eval("var a={}; a;") // {}
eval("var a={};") // undefined
What is the difference between 1; and {}; ?
Left alone, {} is interpreted as a block, not an object. It contains no statements, so does not affect the value of, say, eval("1;{}"). To force it to be interpreted as an object, you can use parentheses:
eval("1;({})"); // {}
It looks to me like eval is interpreting {} as the delimiters of a code block, and therefore has no inherent value.
Related
I have searched but could not find logic behind following in JavaScript.
When I type in the Chrome console:
{} == null
it returns
Uncaught SyntaxError: Unexpected token ==
But
{} == {}
and
{} == function(){}
returns false
Why?
I assume you understand why {} == null throws SyntaxError. Long story short it is because { in the begining starting a block statement not an object literal. You could check the answer here
As of why {} == {} this works.
If you check chromium code that evaluates expressions in console. You could find the following (code)
if (/^\s*\{/.test(text) && /\}\s*$/.test(text))
text = '(' + text + ')';
executionContext.evaluate(text, "console", !!useCommandLineAPI, false, false, true, printResult);
This code wraps {} == {} code with parentheses making it a valid expression ({} == {}) comparing two empty object literals. Which evaluates to false because objects are compared by reference.
Node repl has the same behaviour src
if (/^\s*\{/.test(code) && /\}\s*$/.test(code)) {
// It's confusing for `{ a : 1 }` to be interpreted as a block
// statement rather than an object literal. So, we first try
// to wrap it in parentheses, so that it will be interpreted as
// an expression.
code = `(${code.trim()})\n`;
wrappedCmd = true;
}
You can find this in the specs under Statement (art. 12)
12 - Statement
Statement :
Block.
VariableStatement
EmptyStatement
ExpressionStatement
.
.
.
The first applicable rules are either Block or Expression Statement. So we need to look at 12.4.
In 12.4 the specs clearly state that an expression statement cannot start with a {.
though i haven’t yet found what makes example 2 an expression, maybe it’s implementation specific
12.4 Expression Statement
Syntax
ExpressionStatement :
[lookahead ∉ {{, function}] Expression ;
NOTE An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.
Semantics
The production ExpressionStatement : [lookahead ∉ {{, function}]Expression; is evaluated as follows:
Let exprRef be the result of evaluating Expression.
Return (normal, GetValue(exprRef), empty).
I would say this is a parsing issue, rather than a logic issue per se.
In Chrome I get the observed behavior.
In IE I get syntax errors whenever I put {} (or, it seems, any object literal) on the LHS of the ==.
In both browsers, putting () around the expression fixed things. Or first assigning the object to a variable
var x = {}
x == null
I would say it seems to me like a bug in the parsing. Whether that is true in an academic sense would take digging through specs and grammars; the practical answer is, there are simple enough work-arounds that the best bet is to not do that.
It’s because JavaScript sucks
The reason it doesn’t work is because
JavaScript takes the type the comparison is taking from the first object.
For instance
3+”1” = 4
But
“3”+1 = 31
The first example does the operation as a number because the first object is a number
The second example sees a string as the first object and treats the operation as concatenation of a string.
For your example
{} is an object but null can’t be converted to an object
It works the other way because
{} can be represented as a null object.
Sorry for my ignorance on JavaScript basic concepts.
It boils down to this:
Literal - A value found directly in the script. Examples:
3.14
"This is a string"
[2, 4, 6]
Expression - A group of tokens, often literals or identifiers, combined
with operators that can be evaluated to a specific value. Examples:
2.0
"This is a string"
(x + 2) * 4
There is a very clear difference b/w the above two in Javascript.
I happen to read this article. And I am familiar with the difference b/w function declaration & function expression and when to use one over other or vice-versa.
From the same article:
....You might also recall that when evaluating JSON with eval, the string
is usually wrapped with parenthesis — eval('(' + json + ')'). This is
of course done for the same reason — grouping operator, which
parenthesis are, forces JSON brackets to be parsed as expression
rather than as a block:
try {
{ "x": 5 }; // "{" and "}" are parsed as a block
} catch(err) {
// SyntaxError
}
({ "x": 5 }); // grouping operator forces "{" and "}" to be parsed as object literal
So, what difference does it make to parse something as an object literal other than parsing them as a block?
And for what purpose should I consider to make use of grouping character, in context of parsing?
First, don't eval JSON, use JSON.parse on the String source
A block is a "group of expressions" for example,
let x = 0;
if (true) {
// this is a block
++x;
}
However, equally this is also a block
let x = 0;
{ // hi there, I'm a block!
++x;
}
This means when the interpreter sees block notation, it assumes a block even if you do something like this
{ // this is treated as a block
foo: ++x
}
Here, foo acts as a label rather than a property name and if you try to do more complex things with the attempted object literal, you're going to get a Syntax Error.
When you want to write an Object literal ambiguously like this, the solution is to force the interpreter into "expression mode" explicitly by providing parenthesis
({ // this is definately an Object literal
foo: ++x
})
A group that begins with a { and ends with a } is treated as either object literal or a block depending on context*.
Within an expression context the group is interpreted as an object literal. Writing a block within an expression context will generate a syntax error:
// Valid code:
foo = {a:b};
({a:b});
// Syntax errors:
foo = {var a = b};
({var a = b});
Outside of an expression context the group is interpreted as a block. Depending on exactly how the code is written, an object literal written outside of an expression context is either a syntax error or will be interpreted as a label.
*note: In the ECMAscript spec the word "context" is used to mean something specific. My use of the word here is with the general meaning in computer science with regards to parsing.
eval("x={}")
--> {}
eval("{}")
--> undefined
Why is that?
I want to return an object from an evaluated string.
{} is parsed as an empty block statement, not an object literal expression.
To force it to be parsed as an expression, wrap it in parentheses.
{} is interpreted as a block containing no statements, which evaluates as undefined. x={} forces {} to be evaluated as an expression (the empty object) because you can't assign a block to anything. Then the assignment operator returns the value that was assigned.
A cleaner way to get the same effect would be to wrap the expression in parentheses. eval("({})") gives the right result for me.
eval("{}+{}")
There's lots of errors in JavaScript.
Source: https://www.destroyallsoftware.com/talks/wat
{}[true] is [true] and ![true] should be false.
So why does !{}[true] evaluate to true?
I believe that's because plain {}[true] is parsed as an empty statement block (not an object literal) followed by an array containing true, which is true.
On the other hand, applying the ! operator makes the parser interpret {} as an object literal, so the following {}[true] becomes a member access that returns undefined, and !{}[true] is indeed true (as !undefined is true).
Because {}[true] does not return true, but undefined, and undefined is evaluated as false:
http://jsfiddle.net/67GEu/
'use strict';
var b = {}[true];
alert(b); // undefined
b = !{}[true];
alert(b); // true
Because
{}[true]
evaluates to undefined, and !undefined is true.
From #schlingel:
true is used as key and {} as hash map. There doesn't exist an property with the key true so it returns undefined. Not undefined is true, as expected.
Console session (Node.js [0.10.17]):
> {}[true]
undefined
> !{}[true]
true
> [true]
[ true ]
> ![true]
false
>
However, in the Google Chrome console:
> !{}[true]
true
So, no inconsistencies. You're probably using an old version of the JavaScript VM. For those who need further evidence:
UPDATE
With Firefox, it also evaluates to true:
The reason for the confusion is down to a misunderstanding of your first assertion:
{}[true] is [true]
What you're seeing when you run it is the result of an ambiguity. Javascript has a defined set of rules as to how to handle ambiguities like this, and in this case, it breaks what you see as a signle statement down into two separate statements.
So Javascript sees the above code as two separate statements: Firstly, there is a {}, and then there is an entirely separate [true]. The second statement is what is giving you the result [true]. The first statement {} is effetively entirely ignored.
You can prove this by trying the following:
({}[true])
ie wrapping the whole thing in brackets to force the interpreter to read it as a single statement.
Now you'll see that the actual value of your statement is undefined. (this will also help us later to understand the next part)
Now we know that the initial part of your question is a red herring, so let's move onto the final part of the question:
So why does !{}[true] evaluate to true?
Here, we have the same statement, but with a ! appended to the front of it.
In this case, Javascript's rules tell it to evaluates the entire thing as a single statement.
Refer back to what happened when we wrapped the earlier statement in brackets; we got undefined. This time, we are effectively doing the same thing, but putting a ! in front of it. So your code can be simplified as !undefined, which is true.
Hopefully that explains it a bit.
It is a complex beast, but the lesson to learn here is to use brackets around your statements when evaluating them in the console, to avoid spurious results like this.
{}[true] is undefined. To find that write this:
a = {};
a[true] === undefined // true
or simply:
({})[true] === undefined // true
We know that !undefined is true.
From #Benjamin Gruenbaum's answer:
Chrome dveloper tools does the following:
try {
if (injectCommandLineAPI && inspectedWindow.console) {
inspectedWindow.console._commandLineAPI = new CommandLineAPI(this._commandLineAPIImpl, isEvalOnCallFrame ? object : null);
expression = "with ((window && window.console && window.console._commandLineAPI) || {}) {\n" + expression + "\n}";
}
var result = evalFunction.call(object, expression);
if (objectGroup === "console")
this._lastResult = result;
return result;
}
finally {
if (injectCommandLineAPI && inspectedWindow.console)
delete inspectedWindow.console._commandLineAPI;
}
So basically, it performs a call on the object with the expression. The expression being:
with ((window && window.console && window.console._commandLineAPI) || {}) {
{}+{};// <-- This is your code
}
So, as you can see, the expression is being evaluted directly, without the wrapping parenthesis.
More information can be found in this question.
The answers here are good, here's a breakdown in pseudo-code:
{}['whatever'] = empty block, NewArray('whatever') = NewArray('whatever')
{}[true] = empty block, NewArray(true) = NewArray(true)
!{}['whatever'] = LogicalNOT(convertToBool(NewObject.whatever)) = LogicalNOT(convertToBool(undefined)) = LogicalNOT(false) = true
({}['whatever']) = Grouping(NewObject.whatever) = Grouping(undefined) = undefined
This happens because {} in your meaning is not literal presentation of Object, but empty scope ( or empty code block ):
{ var a = 1 }[true] // [true] (do the same thing)
It just evaluates code inside scope and then shows you your array.
And from your
!{}[true]
Just converts to int this scope and return same array true. There is no bool checks in this code.
And if you will try to check result from {}[true] you will get your false:
{}[true] -> [true] -> ![true] -> false
As there is no more any scope.
So ! in your question do the same as:
!function() {
//...
}
{} is an object with no properties.
Since [] immediately follows an object, it means "Access a property of this name" and not "Create an array"
true is a boolean, but is being used as an property name so it is cast to a string ("true")
The object does not have a property called true (since it has no properties) so {}['true'] is undefined
!undefined casts undefined to a boolean (false)
The not operator turns false into true.
You're not reversing the value of it.
![true] != [!true]
Check this out: Why is !true ? 'false' : 'true' returning 'true'?
Let's Play a Little More!
First, let's have some fun!:
//----------#01#-----------
{}[true]; //[true]
//----------#02#-----------
var a = {}[true];
console.log(a); //undefined
//----------#03#-----------
{ b: 12345 }[true]; //[true]
//----------#04#-----------
{ b: 12345 }["b"]; //evaluates to ["b"] ?!?
//----------#05#-----------
{ b: 12345 }.b; // "Unexpected token ."
//----------#06#-----------
({ b: 12345 }).b; //12345
//----------#07#-----------
var c = { b: 12345 }.b;
console.log(c); //12345
//----------#08#-----------
var c = { b: 12345 }["b"];
console.log(c); //12345
//----------#09#-----------
{ true: 54321 }[true]; // "SyntaxError: Unexpected token : "
//----------#10#-----------
var d = { true: 54321 }[true]; //No error here ¬¬
console.log(d); //54321
//----------#11#-----------
!{}[true]; // true
Ok, let's try to understand these crazy behaviors, one by one:
1) Here, the {} is parsed as an empty code block. Without an assign, negation, grouping (with parentheses) or any syntax which indicates to the parser that this {} is an object literal, the default assumption is to think it is simply a useless empty block.
This is a proof of this behavior:
{ alert(123) }[true]
The code above will show the alert normally, and will be evaluated as [true], in the same way {}[true] is.
Block Statements Without Semicolons
A block-type statement doesn't need a semicolon after it.
For instance:
for(var i=0; i < 1; i++){}function a(){};alert("Passed here!");if(true){}alert("Passed here too!")
Both alerts are shown.
So, we can see that an empty block statement, without a semicolon, is valid and simply does nothing. This way, when you enter {}[true] in the Developer Tools (or Firebug) Console, the evaluated value will be the value of the last expression statement. In this case, the last expression statement is [true].
2) In an assignment context, the parser will make sure that {} is an object literal. When you do var a = {}[true], you remove any ambiguity and tip the parser off that {} is not a block statement.
So, here, you're trying to get a value with a key "true" from an empty object. Obviously, there's no key-value pair with this key name. This way, the a variable is undefined.
Reserved words as Object keys
ECMAScript 5 allows object keys to be reserved words. So, the following keys are legal:
var obj = {if: 111, for: 222, switch: 333, function: 444, true: 555}
3) The same explanation of example 1. But...
If the { b: 12345 } part is treated as a block statement, what's the type of the b: 12345 statement??
... (?????)
It's a label statement, you already saw it before... It's used in loops and in switch. Here are a few interesting links about label statements: 1, (2)[Best way to break from nested loops in Javascript?, (3)[How to break nested loops in javascript?.
NOTE: Just try to evaluate this:
{a: 1, b: 2} //=>>>SyntaxError: Unexpected token :
Label statements can't be separeted by the comma operator, you would need to separate them with a semicolon. So this is valid: {a: 1; b: 2}
4) See the explanations for the examples 1 and 3...
5) One more time, we have a { b: 12345 } being treated as a code block, and you're trying to access a property of a code block by using the dot notation, and obviously, this is not allowed, and the parser throws an "Unexpected token :" exception.
6) The code is almost identical to the above example, but by surrounding the { b: 12345 } statement with the expression grouping operator, the parser will know that is an object. This way, you'll be able to access the "b" property normally.
7) Remember the example 2, we have an assignment here, the parser knows that { b: 12345 } is an object.
8) Identical to the above example, but instead of the dot notation, here we're using the bracket notation.
9) I already said that this "identifier: value" syntax inside a block statement is a label. But, you also have to know that a label name can't be a reserved keyword (the opposite of object property names). When we tried to define a label called "true", we got a SyntaxError.
10) Again, we're dealing with an object. No problems using reserved words here. =)
11) Finally, we have this: !{}[true]
Let's separate the things here:
a) By doing a negation, we're informing to the parser that the {} is an object.
b) As shown in the example 2, a {} object doesn't have a property called true, so this expression will evaluate to undefined.
c) The final result is the negation of undefined value. Javascript performs implicity type conversion, and undefined value is falsy.
d) So, the negation of false is... true!
In the console of both FF and Chrome, {} is considered undefined until explicitly evaluated:
{}; // undefined
({}); // ▶ Object
Actually, it's a bit less defined than undefined -- it's apparently bad syntax:
{} === undefined; // SyntaxError: Unexpected token ===
{}.constructor; // SyntaxError: Unexpected token .
But not if it's on the other side, in which case it's fine:
"[object Object]" == {}.toString(); // true
Or if it's not the first expression:
undefined + undefined; // NaN
{} + undefined; // NaN
undefined + {}; // "undefined[object Object]"
What gives?
If you use the curly brackets by themselves, it's not an object literal, it's a code block. As the code block doesn't contain any code, evaluating it results in undefined.
Okay, here is my answer. There is nothing new here. I am just linking to (a pretty copy of) the ECMAScript specification for the grammar and showing a few productions to show "why" it parses the way it does. In any case, the behavior is well-defined according to the JavaScript/ECMAScript grammar rules: {} is parsed differently depending upon the "context" it is in.
The JavaScript REPLs ("consoles") start to parse the code in the Statement grammar production or "statement context". (This is actually a lie, it starts at the Program or SourceElements production, but that adds additional constructs to dig through.) Here is a rough grammar breakdown with simplifications and omissions; see the link above for more:
Statement
Block
...
ExpressionStatement
Block
# This is actually { StatementList[optional] }, but this is what
# it amounts to: * means "0 or more".
{ Statement* }
ExpressionStatement
# An ExpressionStatement can't start with "{" or "function" as
# "{" starts a Block and "function" starts a FunctionStatement.
[lookahead ∉ {{, function}]Expression ;
Expression
# This is really PrimaryExpression; I skipped a few steps.
...
( Expression )
Thus (when in "statement context"):
{}
-> Block # with no StatementList (or "0 statements")
-> Statement
And:
({})
-> (Expression)
-> Expression
-> ExpressionStatement # omitted in productions below
-> Statement
This also explains why undefined === {} parses as EXPR === EXPR -> EXPR -> STMT and results in false when evaluated. The {} in this case is in an "expression context".
In the case of {} === undefined it is parsed as {}; === undefined, or BLOCK; BOGUS -> STMT; BOGUS, which is a Syntax Error. However, with the addition of parenthesis this changes: ({} === undefined) is parsed as (EXPR === EXPR) -> (EXPR) -> EXPR -> STMT.
In the case of {} + "hi" it is parsed as {}; + "hi", or BLOCK; + EXPR -> STMT; EXPR -> STMT; STMT, which is valid syntax even though it is silly (+ is unary in this case). Likewise, just as above, "hi" + {} puts the {} into an "expression context" and it is parsed as EXPR + EXPR -> EXPR -> STMT.
The JavaScript console is just showing the result of the last Statement, which is "undefined" (well, "nothing" really, but that doesn't exist) for an empty {} block. (This might vary between browsers/environments as to what is returned in this case, e.g. last ExpressionStatement only?)
Happy coding.
If you just type {} as input in any console, there is no context to interpret what you want the curly braces to mean, other than it's position. given the fact each input to the console is interpreted as fresh line of code, the opening curly brace is seen as the start of a new block. The closing } is syntactically correct, since an empty block is often used in situations like these:
try
{
//something
}
catch(e)
{}//suppress error
Hence {} will always be undefined when it is on the left hand side, and never spit errors as an empty block is valid code.
It seems like both consoles treat it as an ambiguous condition when the expression starts with {. Maybe it is treated as a dummy block.
Try this:
{} // undefined
undefined === {} // false
Using {} as a right-hand-expression removes the ambiguity.
Also you can see from:
{a:42} // 42
{{a:42}} // 42
{{{a:42}}} // 42
That the outer braces are really treated as a dummy block.
And this doesn't seem to be a console feature. Even eval treats them like that, hinting to the fact that the stuff you type in the console actually get evaluated the same way they would when passed to eval:
eval("{}") // undefined
eval("{alert(42)}") // alerts 42
The problem is that in some cases, javascript sees { and } as opening and closing a /block/. While in other cases, {} is an object. The cases really depend on the context.
Doug Crockford complains about this. That WTF you're getting there is due to the + operator itself. It's used to both to arithmetic and concatenate. In your last line there, you're seeing the + operator convert undefined and the empty object to strings, and concatenating them.
Javascript separates the concept of statements and expressions (languages like C++ or Java do the same).
For example if ... is a statement, and x?y:z is an expression.
Expressions have a value, statements do not.
One problem with Javascript syntax is that {} can be either an expression (and in this case it means an empty object constructor) or a statement (and in this case it means an empty code block... basically a NOP) so how it's interpreted depends on the context.