
Statements and expressions
An expression produces a value and can be written wherever a value is expected.
Expressions that look like statements
-
Expressions that look like statements
JavaScript has stand-alone blocks? It might surprise you that JavaScript has blocks that can exist on their own (as opposed to being part of a loop or an if statement). The following code illustrates one use case for such blocks: You can give them a label and break from them.
function test(printTwo) {
printing: {
console.log("One");
if (!printTwo) break printing;
console.log("Two");
}
console.log("Three");
} Function expression versus function declaration
function expressions
function() {}
function fn() {}
Using object literals and function expressions as statements
-
eval
parses its argument in statement context. If you wanteval
to return an object, you have to put parentheses around an object literal.> eval("{ foo: 123 }")
123
> eval("({ foo: 123 })")
{ foo: 123 } -
Immediately invoked function expressions (IIFEs)
> (function () { return "abc" }())
'abc'If you omit the parentheses, you get a syntax error (function declarations can’t be anonymous):
> function () { return "abc" }()
SyntaxError: function statement requires a nameIf you add a name, you also get a syntax error (function declarations can’t be immediately invoked):
> function foo() { return "abc" }()
SyntaxError: syntax errorAnother way of guaranteeing that an expression is parsed in expression context is a unary operator such as + or !. But, in contrast to parentheses, these operators change the result of the expression. Which is OK, if you don’t need it:
> +function () { console.log("hello") }()
hello
NaNNaN
is the result of applying + to undefined, the result of calling the function. Brandon Benvie mentions another unary operator that you can use: void [2]:> void function () { console.log("hello") }()
hello
undefined -
Concatenating IIFEs
When you concatenate IIFEs, you must be careful not to forget semicolons:
(function () {}())
(function () {}())
// TypeError: undefined is not a functionThis code produces an error, because JavaScript thinks that the second line is an attempt to call the result of the first line as a function. The fix is to add a semicolon:
(function () {}());
(function () {}())
// OKWith operators that are only unary (plus is both unary and binary), you can omit the semicolon, because automatic semicolon insertion kicks in.
void function () {}()
void function () {}()
// OKJavaScript inserts a semicolon after the first line, because void is not a valid way of continuing this statement [3].