DavidSpot Blog

Developer, super curious, a dog lover, sports fan and techie guy

From C# to Javascript and the problem with return keyword and curly braces position

Many new javascript developers that have some background with C# development some times have problems when returning objects from within a javascript function by putting the curly braces after the return keyword.

Because javascript Semicolon is optional (different from C# or Java witch is required to end a sentence) the javascript interpreter will try to guess where to put when it's not present.

For instance, the code below results in different results:

// Good
return {
    prop : "one"

// Bad!
    prop : "two"

The first one returns an object as expected but the last returns undefined and here is the reason why:

return; // Semicolon inserted, believing the statement has finished. Returns undefined
{ // Considered to be an anonymous block, doing nothing
	prop : "two"
};// Semicolon interpreted as an empty dummy line and moved down

C# developers, that normally use Visual Studio, are used to the default syntax (by default if you use Ctrl + K + D shortcut, visual studio will auto-ident the code for you), witch puts in a new line a curly brace every time with have a class or method and because of this the probability to make have this kind of unexpected error it's big.

My suggestion to avoid this problem is to put the first curly brace always at the end of the line preceded by some other code.