Blog

  • Home /
  • Blog /
  • Basic JavaScript Part 6: Automatic Semicolon Insertion

Basic JavaScript Part 6: Automatic Semicolon Insertion

January 12, 2011

Here are the links to the previous installments:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting

For this post, I’m going to discuss a feature of JavaScript that can easily get you in trouble. Semicolons in JavaScript are not mandatory. This means that if you forget to place a semicolon after some statement, JavaScript isn’t going to complain about it. But most JavaScript engines make up for this lack of consistency by automatically adding a semicolon for you at runtime. This is were you can get in trouble and leave you wondering what is going on. Let’s take a look at the following code snippet:

You might expect that calling this shoeFactory function is going to return an object with a shoeSize property set to the number 48. Wrong! When executing this code, the shoeFactory method actually returns undefined instead of a new object.

What really happens at runtime is this:

The way to get this code to behave properly in this case is by placing the opening curly brace of the object literal at the end of the line that contains the return statement. 

function shoeFactory() {
    return 
    {
        shoeSize: 48
    };
}

var shoe = shoeFactory();
console.log(shoe);

The placement of semicolons might come off as a matter of preference. But the way you outline braces in JavaScript can be very important for your JavaScript code to behave properly. It’s highly recommended to not rely on the automatic semicolon insertion mechanism and to always try to put semicolons on the right place in the code. Also trying to outline curly braces as shown above can save you some headaches in case a semicolon is forgotten somewhere in the code.

That’s it for this one. Until next time.

If you and your team want to learn more about how to write maintainable unit tests and get the most out of TDD practices, make sure to have look at our trainings and workshops or check out the books section. Feel free to reach out at infonull@nullprincipal-itnull.be.

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Author of Writing Maintainable Unit Tests. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be