0

I am new to JavaScript and pretty confused about the role of the ; (semi-colon). I have the following codes that both run smoothly. None of them runs into errors.

Code 1:

const portNumber = 8080;
const app = express();

Code 2:

const portNumber = 8080
const app = express()

So, it appears the semi-colon is not necessary. So why bother about it at all like in Code 1 if I'd rather concentrate on the rest like in Code 2? Is there any sence in using the semi-colon like in Code 1?

Socrates
  • 8,724
  • 25
  • 66
  • 113
  • Sometimes you have to use it, because the automatic semicolon injection doesn't always work – Luca Kiebel May 13 '18 at 11:49
  • 1
    Using semicolons is a good practice for "clean" programming because a lot of other languages require it. Also, without semicolons, older Browser could misinterpret the JS code what would lead to unwanted behavior. – CodeF0x May 13 '18 at 11:49
  • 2
    @CodeF0x - I agree with you about using them, but do you have a citation for semicolon misinterpretation in older browsers? I've never heard of any of them getting the ASI rules wrong. – T.J. Crowder May 13 '18 at 11:50
  • @T.J.Crowder I might be wrong, but I once had a situation when a single missing semicolon led to the code not working properly. That was in IE10 if I remember correctly. – CodeF0x May 13 '18 at 11:58
  • 1
    @CodeF0x: I'm sure IE10 had the rules right, so probably it would have caused trouble on other browsers too. Missing semicolons can definitely make the code not work as expected; that's one reason why it's best to put a `;` between files when concatenating multiple files together. If one ends with `var f = function() { /*... */}` (setting `f` to a function instance without calling it) and the next starts with `(function() { /* ... */ }())`, for instance, without the semicolon you end up the first function getting **called** with the second as an argument (because ASI won't insert `;` there). – T.J. Crowder May 13 '18 at 12:04
  • @T.J.Crowder That makes sense to me. Thank you for pointing it out. – CodeF0x May 13 '18 at 12:06
  • Thanks @CodeF0x and @ TJCrowder. That was the answer! – Socrates May 14 '18 at 07:43

0 Answers0