JS Coding Questions Logo
JS Coding Questions
#178💼 Interview💻 Code

Can you give an example of when you really need a semicolon

Advertisement

728x90

It is recommended to use semicolons after every statement in JavaScript. For example, in the below case (that is an IIFE = Immediately Invoked Function Expression) it throws an error ".. is not a function" at runtime due to missing semicolon.

javascript
1// define a function
2
3var fn = (function () {
4  //...
5})(
6  // semicolon missing at this line
7
8  // then execute some code inside a closure
9  function () {
10  //...
11  }
12)();

and it will be interpreted as

javascript
1var fn = (function () {
2  //...
3  })(function () {
4  //...
5  })();

In this case, we are passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. Hence, the second function will fail with a "... is not a function" error at runtime.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 7

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
178of476
Can you give an example of when you really need a semicolon | JSCodingQuestions.com