Be Careful with Code Formatting
Usually code formatting is a matter of personal preference, with no impact on how code actually works, but there are exceptions.
Let’s start with this if statement:
if (foo) {
// Do something if foo is true.
} else {
// Do something else if foo is false.
}
Some people prefer to format their code differently, and would write the if statement above like this:
if (foo)
{
// Do something if foo is true.
}
else
{
// Do something else if foo is false.
}
So far, so good. This code looks different, but it works exactly the same.
Now let’s look at a function that returns an object:
function foo() {
// Imagine some code here.
return {
property1: value1,
property2: value2
};
}
Good times, no problems here. But what if we try to format this differently, like before?
function foo()
{
// Imagine some code here.
return
{
property1: value1,
property2: value2
};
}
Everything might look fine, but making these formatting changes actually broke the function! Depending on where and how this code is run the foo()
function will either return undefined
or the code will refuse to run at all and throw a syntax error.
Why? It has to do with semicolons!
Yes, you heard me correctly: semicolons! As you may know, semicolons in JavaScript are (mostly) optional. The reason they’re optional is that JavaScript parsers have a step called automatic semicolon insertion (ASI) which inserts semicolons for you. The problem with the function as written above is, after the parser adds semicolons, you get this:
return;
{
property1: value1,
property2: value2
};
So now you’ve got a return
statement with nothing attached, meaning one of two things will happen:
- The function will return
undefined
when it hits thereturn
statement and the code following it will never be run. - The parser will throw a syntax error when parsing the code because there’s an object hanging out down there doing nothing, and will refuse to even run the code in the first place.
This also applies to arrays. This is okay:
return [
value1,
value2
];
But this is not:
return
[
value1,
value2
];
So, regardless of how you format your code, watch out for situations like this. Generally speaking, you’re fine formatting blocks and scopes however you wish; however, object and array literals may need to be treated differently depending on your preferred style.