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.
Related
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.
This question already has answers here:
Why does JavaScript's eval need parentheses to eval JSON data?
(7 answers)
Closed 7 years ago.
If I run this:
eval('{ear: {"<=": 6}}');
I get an error:
Uncaught SyntaxError: Unexpected token :
Let's create the object manually:
var foo = {};
foo.ear = {};
foo.ear["<="] = 6;
Now, the following code:
JSON.stringify(foo)
Returns the following string:
'{"ear":{"<=":6}}'
The same string as the one I started with (except the white characters, but those are irrelevant), so eval(JSON.stringify(foo)) returns the same syntax error error message. However:
$.parseJSON(JSON.stringify(foo))
is executed correctly. What is the reason of that?
EDIT:
As nnnnnn and Ron Dadon pointed out, the initial string and the result of stringify are different. However, as I pointed out in the question, even the result of stringify used as input for eval will result in the syntax error message.
EDIT2:
Based on the answers and experiments conducted, this function is interesting:
function evalJSON(text) {
return eval("(" + text + ")");
}
Main {} are parsed as block statement.
try to wrap in parenthesis:
eval('({ear: {"<=": 6}})');
In javascript {} can be parsed as a block or an object
examples:
//object
var user = {
name: "John",
age: "32"
};
//block
{
let a = 5;
console.log(a);
}
//object:
var a = {};
console.log({});
return {};
({});
//block:
function(){}
for(k in o){}
{}
Object literal notations need to be evaluated. This happens when you assign a variable:
var a = {ear: {"<=": 6}};
or when you put parentheses around it, a anonymous object:
({ear: {"<=": 6}});
Otherwise curly brackets are parsed as block markers. In your case this means {ear:...} is a label definition, the label is named ear. The next block {"<=": 6} gives you a syntax error because "<=": 6 is invalid syntax.
The same applies if you put this into an eval statement.
It's not flawed. To understand what is happening you need to understand what kind of statements are seen (left to right) by the parser.
A simple way to get into it is to play around with a Javascript AST Visualizer
You will get the same exception with much simpler {"b":4}. It's parsed as "b":4 inside a block. That's not valid javascript. No AST tree for you...
However it's due to an exception inside of a {} statement. That's a BlockStatement. AST tree:
A similar {b:4} would be understood as b:4, a valid js statement - a b label for 4... That's parsed as
Lastly, a ({b:4}) would be understood as an object declaration with a b property equal to 4. That's parsed as
ECMAScript 2015
On Blocks:
Block : { StatementList }
On eval itself:
Eval creates a new Realm, which is parsed (several steps here) as a sequence of Statements ( a StatementList ), which in turn this section has BlockStatement as a first option. This must start with { (see above), so if you wrap it with a bracket (({})) it cannot be a BlockStatement... But if it matches as BlockStatement it must be a BlockStatement.
A side note in section on Expressions:
An ExpressionStatement cannot start with a U+007B (LEFT CURLY BRACKET) because that might make it ambiguous with a Block
{}[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!
This question already has answers here:
JavaScript plus sign in front of function expression
(4 answers)
Closed 8 years ago.
I was going through a piece of code here http://cssdeck.com/labs/bjiau4dy and I saw this in the Javascript box -
!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!
What does that do ? and why does it not throw errors in the console ?
Thanks!
Any of those symbols turn the function that follows it into a function expression, instead of a function declaration. Putting them all in there together is just for fun.
If you try to call a regular function by putting () right after the declaration:
function () {
// this is a syntax error...
}();
you'll get a syntax error:
SyntaxError: Unexpected token (
since you cannot call a function declaration.
So people usually wrap an anonymous function in parentheses to turn it into a function expression:
(function () {
// this will execute immediately
}());
You can achieve the same thing be prepending any of those symbols:
!function () {
// this will also execute immediately
}();
For more information, see here: http://kangax.github.com/nfe/#expr-vs-decl
There is zero point to doing the long set of symbols except as a stylistic watermark.
That set of symbols acts as an operation on the function that follows, but does nothing.
In JS you can write 1 or +1 (one) or !1 (false) or !+1 (still false). This is just a long chain of those that are acting on the following function.
So !+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!1 doesn't throw an error. Its value is false though.
And !+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!function(){ ... } just executes the function and evaluates to false (but nothing is done with the value anyway)
However, since something is there, it turns the function definition into an operation and evaluates the function immediately. But just +function(){ ... } would do the same thing.
To elaborate a bit more, each of these operators will actually perform type coercion on the operand proceeding it. + will convert the operand following it into a number, as will the - operator. ! is the not operator, and will convert the operand into a boolean (true/false).
Another thing to bear in mind is that in Javascript, everything can have evaluate to some kind of value. That could be a "truthy" or "falsey" value, and can also have a "number" value (even if that value is not a number, AKA NaN).
So, if you open up JSFiddle, or Firebug, and mess around with what these values do to functions, you can see that they'll also yield some kind of new return value.
For example:
!function(){} will evaluate to a value of false (since coercing a function object to a boolean yields a value of true).
+function(){} will evaluate to a value of NaN (since coercing a function object to a number yields NaN). The same result can be seen by using -.
!+function(){} yields true (coercing a number of value NaN will yield false and not false yields true.
!+-+-+!function(){} yields true (because !function(){} yields false, +false yields 0, and will continue to throughout all those + and - operators until finally !0 is evaluated to true).
Applying the operators like they're listed in your example will go back and forth between false, -1, 0, 1, true until all of the operators have been evaluated.
Note that I checked these using Firebug. There could possibly be differences between browsers, and perhaps what Firebug shows us on evaluation. The TL;DR is that Javascript does lots of type coercion, and will evaluate expressions differently than declarations.
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.