Why JavaScript is doing this to us?

ninja-with-nunchaku There are two bracing techniques/styles in      c-like languages:


Foo() {


I’ve seen both used in C# and in JavaScript, but it was always interesting why last one is much more popular in JavaScript and first one in C# and C++. Now I have the answer:

Putting braces on the same line after statement prevents from doing silly JavaScript mistakes, possible thanks to ECMASrcipt standard.

It states the following:

Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

And a little demo of what they mean:

function FooA() {
		x: 8

function FooB() {
		x: 8

function Bar() {

When calling Bar() function you will see “undefined” and then “8” . This happens because JavaScript is too smart and put semicolon after first return statement (predicting your intent, that is actually should be a marketing slogan), so your anonymous object declaration will never be executed. Why? Here is a little intriguing pause and some dummy text that takes a little more time to read… And finally the answer is: “For convenience”, as told us by ECMA. Enjoy and don’t forget to feel convenient =)

RSS Feed
blog comments powered by Disqus



Find it!

Theme Design by