Where do you place squiggly braces in JavaScript?

While writing code, we developers often tend to learn a programming style and stick to it. You may know a developer (including yourself), who is quite strict about where to add the squiggly braces (brackets) for a function/method, either left or right. There are some people who are quite emotionally attached with styles that they have followed for some time and don’t want to change it in any case. If you are use to writing braces on the left, maybe due to it looks cleaner, you may get into trouble if you are a JavaScript developer. Don’t believe me? Keep reading.

One of the good parts of JavaScript is that you can form an object very easily. Look at the return statement for the function below which just returns an object literal with a greeting message.

If you run this piece of code in the fiddle, you will see that there are no compile or runtime errors in the developer console. You will see two messages logged in the console:

At first, you may think that this is quite weird as I did! I spent some time reloading the page, replacing log function with alert, and what not. But nothing helped. Stop reading and spend some time to figure out the reason of undefined message that is logged, which is obviously not the expected message.

Did you scratched your head or yelled at someone?

JavaScript automatically adds a semicolon i.e. ‘;’ for you after every code statement you write without a semicolon. Now, look at the return statement in the code above. You can’t see it but a semicolon was added for you. This results in returning undefined  from the function to the caller. How weird is that? Because if you don’t know this concept, you will waste some or more time to figure out this issue as no doubt, the code looks clean and also runs without any compile-time or runtime errors. Look at the code with output below or use this fiddle to see the correct version of the code.

So, no matter what programming style your guts tell you to follow, always use the braces at the right-side to avoid getting in trouble when using JavaScript. As you may not find the error at the time of writing your code but you may spend good time to find out the actual issue. Hope this concept will save you time.

Siddharth Pandey

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.

You may also like...

Advertisment ad adsense adlogger