sawa
sawa

Reputation: 2050

Why is semicolon required for this statement?

The following code returns an error that says "console.log(...) is not a function"

if (4<5) console.log('hi') 
(4<5) ? console.log('hi') : console.log('bye')

The following code does not return any error

if (4<5) console.log('hi')
if (4<5) console.log('hi')

Why is this so?

Upvotes: 0

Views: 502

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073978

Without a semicolon at the end of the first line, the code tries to use return value of the first console.log as a function and call it with the argument 4<5; this is clearer if you remove the line break:

if (4<5) console.log('hi')(4<5) ? console.log('hi') : console.log('bye')
//       ^^^^^^^^^^^^^^^^^^^^^^---- looks like calling `console.log` and then
//                                  using the result as a function

There's the potential for this any time you combine leaving off semicolons (which means you're relying on an error-correction mechanism1) with expression statements. Since expression statements are, by their nature, expressions, if the parser can use them in the previous expression or statement, it will.


FWIW, astexplorer.net is a cool tool I've recently found (thanks to the Babel project). It's an interactive syntax tree explorer which can use any of several parsers to parse your code and tell you exactly how it was parsed. And from the github account, it was started by our own Felix Kling.


1 Quoting Brendan Eich:

ASI is (formally speaking) a syntactic error correction procedure. If you start to code as if it were a universal significant-newline rule, you will get into trouble.

Upvotes: 5

Related Questions