Javascript don't like curly bracket in their own line

Today I ran into this piece of code

From time to time, unexpected behavior can popup while programming.
Here is one I would like to write down.

1
2
3
4
5
6
module.exports = function()
{
return {
factoryObject: "Factory made"
}
}

It is an object factory.
It will return an object that have one member, factoryObject which is a string containing Factory made inside it when the unnamed function being called by other scripts.

The following code won’t run in Node.js v5.5.0

1
2
3
4
5
6
7
module.exports = function()
{
return
{
factoryObject: "Factory made"
}
}

The code will crash ultimately with following error:

1
2
3
4
5
6
7
8
9
10
TypeError: Cannot read property 'factoryObject' of undefined
  at Object.<anonymous> (C:\Users\whoami\Desktop\nodejs_projects\import.js:17:20)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:139:18)
at node.js:999:3
<<< Process finished. (Exit code 1)

So we learned an important lesson here.

Conclusion

The real reason is actually the automatic semicolon insertion .
Just don’t put curly bracket in their own line, expesically when the line above can be valid itself.
For example return.