JavaScript for C# Developers: 5. Curly Brace Formatting and the Implicit Semicolon

Category: JavaScript
Last Modified: May 2 2017
Oct 27 2015

In C type languages, such as C, C++, Java and C#, whether the curly brace starts on the same line or on a new line is basically a matter of convention.

function foo() { }  function foo()  { } 

However in JavaScript it does make a difference due to a feature of JavaScript called the “implicit semicolon”, If a statement doesn’t end in a semicolon then JavaScript interpreters will add one.

Lets look at a function to see how this affects the results.

function foo () {   return     {       foo: 1     } } 

At first glance this function would appear to return 1, but becuase an implict semicolon is added after the return statement it returns undefined

function foo () {   return ;     {       foo: 1     } } 

Thus it is a good practice in JavaScript to use the K&R style of curly braces.

function foo () {   return {       foo: 1     } } 

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Tags