Why is a semicolon required at end of line?

2019-02-16 17:15发布

Why does this work:

a = []
a.push(['test']);
(function() {alert('poop')})()

But this gives the error "number is not a function":

a = []
a.push(['test'])
(function() {alert('poop')})()

The only difference is the semicolon at the end of line 2. I've been writing Javascript for a long time now. I know about automatic semicolon insertion, but I can't figure out what would be causing this error.

7条回答
该账号已被封号
2楼-- · 2019-02-16 17:55

Because

a.push(['test'])(function() {alert('poop')})()

is a valid JavaScript expression. And if some adjacent lines can be stick together to form a valid JavaScript expression, your JavaScript engine will stick them together.

Though it is a valid JavaScript expression, a.push returns a number, which is not a function, and when you try to call something that is not a function, it returns the error you see.

查看更多
登录 后发表回答