InterviewHubPRO
Section Overview
Q182

Question 182 of 521

Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

35%
JavaScript Internals (521 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

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

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
  // define a function
  var fn = (function () {
    //...
  })(
    // semicolon missing at this line

    // then execute some code inside a closure
    function () {
      //...
    }
  )();

and it will be interpreted as

javascript
  var fn = (function () {
    //...
  })(function () {
    //...
  })();

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.