【转】Expressions versus statements in JavaScript
原文地址:http://www.2ality.com/2012/09/expressions-vs-statements.html
Update 2012-09-21: New in Sect. 4: using void for IIFEs, concatenating IIFEs.
This blog post looks at a syntactic distinction that is unfortunately quite important in JavaScript: the difference between expressions and statements.
Statements and expressions
JavaScript distinguishes expressions and statements. An expression produces a value and can be written wherever a value is expected, for example as an argument in a function call. Each of the following lines contains an expression:
myvar
3 + x
myfunc("a", "b")
Roughly, a statement performs an action. Loops and if statements are examples of statements. A program is basically a sequence of statements (we’re ignoring declarations here). Wherever JavaScript expects a statement, you can also write an expression. Such a statement is called an 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.
Similar kinds of statements and expressions
The difference between statements and expressions becomes clearer if we look at members of the two syntactic categories that are similar.
If statement versus conditional operator
The following is an example of an if statement:
var x;
if (y >= 0) {
x = y;
} else {
x = -y;
}
Expressions have an analog, the conditional operator. The above statements are equivalent to the following statement.
var x = (y >= 0 ? y : -y);
The code between the equals sign and the semicolon is an expression. The parentheses are not necessary, but I find the conditional operator easier to read if I put it in parens.
Semicolon versus comma operator
In JavaScript, one uses the semicolon to chain statements:
foo(); bar()
For expressions, there is the lesser-known comma operator:
foo(), bar()
That operator evaluates both expressions and returns the result of the second one. Examples:
> "a", "b"
'b' > var x = ("a", "b");
> x
'b' > console.log(("a", "b"));
b
Expressions that look like statements
Some expressions look like statements. We’ll examine why that is a problem at the end of this section.
Object literal versus block
The following is an object literal, an expression that produces an object.
{
foo: bar(3, 5)
}
However, it is also a perfectly legal statement, with these components:
- A block: a sequence of statements in curly braces.
- A label: you can prefix any statement with a label. Here the label is foo.
- A statement: the expression statement bar(3, 5).
{} being either a block or an object literal is responsible for the following WAT:
> [] + {}
"[object Object]"
> {} + []
0
Given that the plus operator is commutative, shouldn’t these two (expression) statements return the same result? No, because the second statement is equivalent to a code block followed by +[]:
> +[]
0
For details on this and other WAT phenomena, consult [1].
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");
}
Interaction:
> test(false)
One
Three > test(true)
One
Two
Three
Function expression versus function declaration
The code below is a function expression:
function () { }
You can also give a function expression a name and turn it into a named function expression:
function foo() { }
The function name (foo, above) only exists inside the function and can, for example, be used for self-recursion:
> var fac = function me(x) { return x <= 1 ? 1 : x * me(x-1) }
> fac(10)
3628800
> console.log(me)
ReferenceError: me is not defined
A named function expression is indistinguishable from a function declaration (which is, roughly, a statement). But their effects are different: A function expression produces a value (the function). A function declaration leads to an action – the creation of a variable whose value is the function. Furthermore, only a function expression can be immediately invoked, but not a function declaration.
Using object literals and function expressions as statements
We have seen that some expressions are indistinguishable from statements. That means that the same code works differently depending on whether it appears in an expression context or a statement context. Normally the two contexts are clearly separated. However, with expression statements, there is an overlap: There, you have expressions that appear in a statement context. In order to prevent ambiguity, the JavaScript grammar forbids expression statements to start with a curly brace or with the keywordfunction:
ExpressionStatement :
[lookahead ∉ {"{", "function"}] Expression ;
So what do you do if you want to write an expression statement that starts with either of those two tokens? You can put it in parentheses, which does not change its result, but ensures that it appears in an expression-only context. Let’s look at two examples: evaland immediately invoked function expressions.
eval
eval parses its argument in statement context. If you want eval 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)
The following code is an immediately invoked function expression.
> (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 name
If you add a name, you also get a syntax error (function declarations can’t be immediately invoked):
> function foo() { return "abc" }()
SyntaxError: syntax error
Another 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
NaN
NaN 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 function
This 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 () {}())
// OK
With 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 () {}()
// OK
JavaScript inserts a semicolon after the first line, because void is not a valid way of continuing this statement [3].
Related posts
- What is {} + {} in JavaScript?
- The void operator in JavaScript
- Automatic semicolon insertion in JavaScript
【转】Expressions versus statements in JavaScript的更多相关文章
- Expressions versus statements in JavaScript
Statements and expressions An expression produces a value and can be written wherever a value is exp ...
- JavaScript简易教程(转)
原文:http://www.cnblogs.com/yanhaijing/p/3685304.html 这是我所知道的最完整最简洁的JavaScript基础教程. 这篇文章带你尽快走进JavaScri ...
- 每个JavaScript工程师都应懂的33个概念
摘要: 基础很重要啊! 原文:33 concepts every JavaScript developer should know 译文:每个 JavaScript 工程师都应懂的33个概念 作者:s ...
- JavaScript简易教程
这是我所知道的最完整最简洁的JavaScript基础教程. 这篇文章带你尽快走进JavaScript的世界——前提是你有一些编程经验的话.本文试图描述这门语言的最小子集.我给这个子集起名叫做“Java ...
- 每个 JavaScript 工程师都应懂的33个概念
简介 这个项目是为了帮助开发者掌握 JavaScript 概念而创立的.它不是必备,但在未来学习(JavaScript)中,可以作为一篇指南. 本篇文章是参照 @leonardomso 创立,英文版项 ...
- JavaScript 中表达式和语句的区别
1.语句和表达式 JavaScript中的表达式和语句是有区别的.一个表达式会产生一个值,它可以放在任何需要一个值的地方,比如,作为一个函数调用的参数.下面的每行代码都是一个表达式: myvar3 + ...
- 对JavaScript优化及规范的一些感想
变量...... 1.一个变量只存一种类型的数据,2.尽量减少对隐式转换的依赖,这样可增强程序的可读性,日后修改程序时不至于混乱,3.使用匈牙利命名法,4.使用局部变量时记得加 var 进行声明,不然 ...
- (译)详解javascript立即执行函数表达式(IIFE)
写在前面 这是一篇译文,原文:Immediately-Invoked Function Expression (IIFE) 原文是一篇很经典的讲解IIFE的文章,很适合收藏.本文虽然是译文,但是直译的 ...
- [转]Javascript中的自执行函数表达式
[转]Javascript中的自执行函数表达式 本文转载自:http://www.ghugo.com/javascript-auto-run-function/ 以下是正文: Posted on 20 ...
随机推荐
- NodeJ node.js Jquery Ajax 跨域请求
Jquery + Ajax 跨域请求 说白了就是前台请求ajax数据(JSON)但是请求的数据不在本地的绝对路径下,接口数据 是没有这个安全性的我对外公开的接口数据,只要你找到接口你就可以使用里面的数 ...
- kali linux 安装TIM or QQ(CrossOver 安装 QQ)
需要文件 http://www.crossoverchina.com/xiazai.html dpkg --add-architecture i386 apt-get update apt-get i ...
- 【模板】负环(spfa)
题目描述 暴力枚举/SPFA/Bellman-ford/奇怪的贪心/超神搜索 输入输出格式 输入格式: 第一行一个正整数T表示数据组数,对于每组数据: 第一行两个正整数N M,表示图有N个顶点,M条边 ...
- 【模板】缩点(tarjan,DAG上DP)
题目背景 缩点+DP 题目描述 给定一个n个点m条边有向图,每个点有一个权值,求一条路径,使路径经过的点权值之和最大.你只需要求出这个权值和. 允许多次经过一条边或者一个点,但是,重复经过的点,权值只 ...
- 用VMWare搭建服务器集群不能上外网的三种模式下对应解决办法
前言 决心要花费宝贵时间写下这篇心得,是因为从昨天晚上到今天上午被这个VMWare模拟搭建的服务器集群不能上外网的问题搞得很心烦,最后决定跟它杠上了!上午还通过远程连接得到了“空白”同学的帮助,在此表 ...
- cut 的用法
cut 文件内容查看 显示行中的指定部分,删除文件中指定字段 显示文件的内容,类似于下的type命令. 说明 该命令有两项功能,其一是用来显示文件的内容,它依次读取由参数file所指明的文件,将它们的 ...
- 谈个人对avascript面向对象的理解
javascript,不但是javascript或者是别的语音,大多数都有一句经典的话:一切皆对象. 下面谈谈我个人对面向对象的理解,为什么要用面向对象来写js,这话我思考了很久,最后得出的结论就是: ...
- 20190118-利用Python实现Pig Latin游戏
1.利用Python实现Pig Latin字母游戏 “Pig Latin”是一个英语儿童文字改写游戏,整个游戏遵从下述规则:a. 元音字母是‘a’.‘e’.‘i’.‘o’.‘u’.字母‘y’在不是第一 ...
- Python学习 :装饰器
装饰器(函数) 装饰器作为一个函数,可以为其他函数在不修改原函数代码的前提下添加新的功能 装饰器的返回值是一个函数对象.它经常用于有切面需求的场景,比如:插入日志.性能测试.事务处理.缓存.权限校验等 ...
- VIM 键
输入 vimtutor命令,可以打开Linux使用手册(基本使用). ***. 插入键: A: 行尾插入 a: 字符后面插入 i: 字符前面插入 I: 行首插入 r:只替换一次字符 R:一直替换,直 ...