FrontendDeveloper.in

JavaScript question detail

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.

// 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

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.

Back to all JavaScript questions
Get LinkedIn Premium at Rs 399