This blog is about how JavaScript parses your script (source code) when it encounters a return statement. We can write code using any one style of the following two:
Style 1:
1
2
3
| function func() { return 6 ; } |
and
Style 2:
1
2
3
4
| function func() { return 6 ; } |
And people usually say that this is a matter of personal preference. But watch out! Here’s the catch. You can’t always put an opening curly brace on the next line just after the return statement. For example, if you want to return an object from the function then the following code will not work:
1
2
3
4
5
6
| function func() { return { "key" : "value" }; } |
It’ll throw SyntaxError. The reason is how JavaScript interprets its source code file. As we all know semicolon at line end is optional, and in this optional case JavaScript parser tries to break the physical line to logical line using newline character, and this problem begins. So the correct way is as follows:
either this:
1
2
3
4
5
| function func() { return { "key" : "value" }; } |
or like this:
1
2
3
4
5
6
| function func() { return { "key" : "value" }; } |
So folks, never put an opening curly brace on the next line just after a return statement, whether you like it or not!
No comments:
Post a Comment
If you have any doubts or questions, please let us know.