Code Like A Girl

Welcome to Code Like A Girl, a space that celebrates redefining society's perceptions of women in technology. Share your story with us!

Follow publication

Why The Heck Do I Need To Use Semi-Colons in Javascript

TL;DR: Semi-colons are optional in Javascript, but omitting them can lead to dire consequences on rare occasions. This post explains the reasoning behind when and why to use them for beginners, and signposts to further reading for more detailed information.

IMAGE DESCRIPTION: Morpheus from The Matrix with the caption ‘What if I told you… semi colons in javascript are optional”

I started learning Javascript last week. I’ve seen it before, and done a couple of online lessons a few months ago, but never really written my own JS code from scratch, or without single prompts like “write a function that does x and returns y, using z method, like the example above”. Honestly? From a background of Ruby, Javascript seems kind of bananas. In my opinion this is due to:

- syntactic and grammatical changes (moving from learning one language to a different one)
- there are multiple ways of doing a thing in JS
- trying to get my head around anything that isn’t straight object-oriented programming

There’s a really fundamental aspect of the syntax that’s got me all discombobulated. When do I use a semi-colon? Everyone else seems to be using them in the right places, but I can’t work out what the right places are. Sometimes they’re there, and sometimes they aren’t.

I know I can get away with not using them at all (avert your eyes, instructors):

IMAGE DESCRIPTION: A long excerpt from my text editor today showing multiple JS functions with nary a semi-colon in sight

But… I may well be setting myself up for problems in the future by assuming this is an ok default. In the programming community, there are people in both camps (some who use semi colons, some who don’t) and some who decide on a case-by-case basis.

The official guidelines

The official guidelines say that JS uses a semi colon to terminate a statement.

The ECMAScript spec describes how, if a statement is not explicitly terminated with a semicolon, sometimes a semicolon will be automatically inserted by JavaScript engine (called “Automatic Semicolon Insertion” (ASI)). There’s a really good post here which outlines the three scenarios where this happens (it would be a messy injustice for me to try and rewrite it).

So, if you don’t physically put them in, the engine will do it for you. It just happens behind the scenes. ASI helps the parser to determine when a statement ends.

Semi colons aren’t required, but have been considered best practice for a long time. Sounds pretty archaic to me.

IMAGE DESCRIPTION: Altered screengrabs, originally from the film “Office Space”, show two middle aged men in suits having a serious and slightly threatening conversation with a young employee who has been missing semi colons in his code.

What’s a statement? How is it different to an expression?

In JS, this syntactic distinction is important. Roughly, a statement performs an action, and an expression produces a value. Wherever something is doing something, that’s a statement. Wherever a value is expected, that’s an expression.

IMAGE DESCRIPTION: Winona Ryder looks confused as complex maths equations float above her head.

The CliffsNotes version for the most frequent times a beginner developer is likely to need semi colons:

All of these statements can end with a semi colon, but none of them must:

const i;                      // variable declaration
i = 5; // value assignment
i = i + 1; // value assignment
i++; // same as above
var x = 9; // declaration & assignment
var fun = function() {...}; // var decl., assign., & func. defin.
alert("hello, world!"); // function call

However, if you’re going to put two statements on the same line, you have to separate them with a semi colon:

let i = 0; i++                 // <-- semi colon obligatory

And! You shouldn’t put semi colons after curly brackets, except assignment statements, like var obj = {};

The last quirk to note is that inside a for loop, you only need semi colons after the first two statements, but not the third:

for (var i=0; i < 10; i++) {/*stuff*/} // correct
for (var i=0; i < 10; i++;) {/*stuff*/} // SyntaxError

RECAP:
MOST COMMON ‘DO SEMI COLON WHEN’ RULES

  • two statements are on the same line
  • in the first two statements of a for loop, but not the third

There is also the argument that you can lead, or start, any statement beginning with ( or [ with a semi colon, as opposed to finishing the line before it with one. This is called ‘defensive semi colon’-ing, and still does the job of separating the two lines for the parser, so it can see there are two separate statements, rather than just a continuation of whatever statement was on the previous line. Starting a line with a semi colon feels a bit odd though, and doesn’t seem to have caught on much.

Conclusion

Don’t think that just by whacking semi colons in everywhere you’re safe from bugs. This post outlines how ASI can still mess your code up even if you’re in the “never omit” camp. You should put effort and practice into understanding the reasoning.

I think I’m going to need a lot of reiteration with JS to really fine-tune my understanding of when I absolutely need to use a semi colon to avoid bugs, but this is a good place to start my learning. And it means I can go back to not using them (which is my preference) with a slightly clearer conscience.

Don’t let anyone tell you you’re a bad developer if you understand why semi colons are used in JS and choose not to use them.

IMAGE DESCRIPTION: Garth Algar says “we fear change” and smashes an animatronic hand with a hammer.

Just be consistent.

References:
https://hackernoon.com/an-open-letter-to-javascript-leaders-regarding-no-semicolons-82cec422d67d

https://news.codecademy.com/your-guide-to-semicolons-in-javascript/

http://www.bradoncode.com/blog/2015/08/26/javascript-semi-colon-insertion/

http://2ality.com/2012/09/expressions-vs-statements.html

PS: try using JSLint. I was told: “it will hurt your feelings, but it will be good for you.” It’s the same tool that’s built into the Codecademy JS code editor, but uses actual verbal ‘warnings’ instead of that nice little yellow triangle.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in Code Like A Girl

Welcome to Code Like A Girl, a space that celebrates redefining society's perceptions of women in technology. Share your story with us!

Written by Lucy Mitchell

Technical Writer. Former NHS OT and software developer in health tech. I like bikes and plants. www.ioreka.dev

Responses (3)

Write a response