1. Expression Versus Statements
An expression produces a value and can be written wherever a value is expected.Wherever JavaScript expects a statement, you can also write an expression. Such a statement is called expression statement. The reverse does not hold: you cannot write a statement where JavaScript expects an expression. For example, an if statement cannot become the argument of a function.
conditional operator:
var salutation = (male ? 'Mr.' : 'Mrs.');
Using ambiguous expressions as statements: JavaScript does not let you use object literals and function expressions as statements. That is, expression statements must not start with: A curly brace / The keyword function
Immediately invoking a function expression
> (function () { return 'abc'}())
'abc'
If you omit the parentheses, you get a syntax error, because JavaScript see a function declaration, which can't be anonymous. If you add a name, you also get a syntax error, because function declaration can't be immediately invoked.
2. Rules for Using Semicolons
Normally, statements are terminated by semicolons.The following statements are not terminated by semicolons if they end with a block.
Loops: for, while(but not do-while)
Branching: if, switch, try
Function declarations(but not function expressions)
while versus do-while:
while (a > 0) {
a--;
} // no semicolon
do {
a--;
} while (a > 0);
function declaration versus function expression:
function foo() {
//...
} // no semicolon
var foo = function () {
//...
};
3. Legal Identifiers
Reserved words are part of the syntax and can't be used as variable names.4. Invoking Methods on Number Literals
It is important to distinguish between the floating-point dot and the method invocation dot. You can't write 1.toString(); you must use the one of the following altrnatives:1..toString()
1 .toString() // space before dot
(1).toString()
1.0.toString()
5. Strict Mode
The normal(nonstrict) mode is sometimes called "sloppy mode".In strict mode, all variables must be expicitly declared.
In strict mode, all functions must be declared at the top level of a scope.
function strictFunc() {
'use strict';
{
//Syntax Error:
function nested() {
}
}
}
function strictFunc() {
'use strict';
{
//OK
var nested = function () {
};
}
}
没有评论:
发表评论