Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

syntax error - JavaScript: {}==false is a SyntaxError?

In Firefox 3.5, I type this in the Firebug console :

false=={} // => evals to false
{}==false // syntax error

What is the explanation for this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
{

at the start of a statement signals a ‘statement block’ (see ECMA-262-3 section 12.1), which contains a list of statements.

}

immediately ends the statement block with no statements in it. That's fine. But now the parser is looking for the next statement:

==false

Huh? That's not a statement; syntax error.

What are statement blocks for? Well, you are writing a statement block every time you say:

if (something) {
    ...
}

JavaScript defines these flow-control statements as:

if "(" <expression> ")" <statement> [else <statement>]

ie. in the single statement form with no braces. It then allows you to use a statement-block anywhere you can use a single statement, which means you can have if-braces-many-statements. But it also means you can have a statement-block on its own with no associated flow-control statement.

This serves absolutely no practical purpose! You might be tempted to think it gave you information-hiding, but no:

var a= 1;
{
    var a= 2;
}
alert(a);

...results in 2, because statement blocks don't in themselves create a new scope.

JavaScript defines flow control and statement blocks in this manner because C (and other languages derived from it) did. Those languages didn't make {} serve double-duty as an Object literal expression though, so they didn't have the ambiguity that makes this another JS misfeature.

Even this wannabe-literal:

{
   a: 1
}

is a valid statement block, because ‘:’ is used to denote a label in a statement. (and 1 is a useless expression-statement, with the semicolon omitted.) Labels are another feature inherited from C that are rarely used in JavaScript. They're not totally pointless like the blocks, but they're seldom needed and often considered in poor taste.

(A literal with two properties will cause a syntax error, as object literals use comma separators, but labelled statements must be separated by semicolons.)

This is not the only place where JavaScript's loose syntax can trip you up by making some other statement of something you think is an expression.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...