Consider the following JavaScript:
function correct()
{
return 15;
}
function wrong()
{
return
15;
}
console.log("correct() called : "+correct());
console.log("wrong() called : "+wrong());
The correct() method in the above code snippet returns the correct value which is 15 in this case. The wrong() method, however returns undefined. Such is not the case with the most other languages.
The following function is however correct and returns the correct value.
function wrong()
{
return(
15);
}
If the syntax is wrong, it should issue some compiler error but it doesn’t. Why does this happen?
Technically, semi colons in javascript are optional. But in reality it just inserts them for you at certain newline characters if it thinks they are missing. But the descisions it makes for you are not always what you actually want.
And a
returnstatement followed by a new line tells the JS intepreter that a semi colon should be inserted after thatreturn. Therefore your actual code is this:Which is obviously wrong. So why does this work?
Well here we start an expression with an open
(. JS knows we are in the middle of an expression when it finds the new line and is smart enough to not insert any semi colons in this case.