Are semicolons required in JavaScript?

PUBLISHED ON MAY 16, 2017 — QUORA

You don’t need semi colons in JavaScript. But don’t try to exploit this fact.

Here is example

var foo = function(n){
	if(n <5) {
		return 
			n*2
	}
	else{
		return n;
			
	}
}
 
foo(6) // returns 6
foo(3) // should return 6 but returns undefined. 

The reason is, on line 3 JS doesn’t see a semi colon and inserts it for you.

Internally it looks up next line and see if it can be a standalone expression (n*2) and unfortunately is does in this case. Hence, you get undefined instead of 6.

A more in depth read is available here.

JavaScript Semicolon Insertion


Originally Written on Quora.

TAGS: QUORA, TECH