General Object/function question about semi-colons


So this is just kind of a weird thing I found when trying some things in one of the lessons. The lesson doesn't really matter as it applies to anything, so here it is.

I noticed that a semi colon is automatically placed in certain places, or precoded by the teachers who set up the javascript course into certain things like after the closing curly brace in an object's function. If you remove that semi colon no errors are thrown, though. So what's the point? Is it just good grammar, so to speak? Both work, which seems weird to me.

snoopy.bark = function() { console.log("Woof");};


snoopy.bark = function() { console.log("Woof");} 

//both work just fine. No errors, and they perform the purpose of the function 
//just as well as far as I can tell. I don't usually write functions on one line but
// in this case I felt it was easy enough since it wasn't complicated. I don't know 
//if that's bad practice or something but I did it.


syntax/grammer theres a particular way it should be formatted and sometimes it works wihout proper syntax, case in point. if you were to add a function afterwards without the semicolon it would not work correctly. also with lots of languages as the progress in versions they make it easier to do things, and sometimes make the older syntax "obsolete" for lack or a better term. look at all the changes in html from the original version


Javascript adds semi-colons where missing based on some rules.

Consider these functions:

var f = function() {
  // does this function get called?
  console.log('f was called');


var g = function() {
  // and what does this function return?

function h() {
  // what about this one, is it called?
  console.log('h was called')


If you run that code, does f get invoked? h? And if you call g, does it return 3 or undefined?

You can leave them out, but the result might be less clear about what the intention is.

Until you've formed your own well-informed opinion about what style to use, I suggest including the semi-colons for all statements that have them. Look them up if you don't know.

What really matters is that you use a consistent style designed to be readable and avoid subtle mistakes. Whatever style does that for you is the best one.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.