Code formatting. Tabs or spaces, semi-colons or no semi-colons. It is a pretty controversial subject to many but it is quite important in some instances. If you are on a team, having a cohesive code format helps code readability among your peers. Even if you work alone, one big benefit of having a good sense of code formatting is to avoid syntactical errors.
Unexpected end of input error. How does it work?
Unexpected end of input error, odds are you are missing a closing curly brace
} so the error is basically saying “you opened the curly brace but the code ended before it was closed”.
Here’s an example:
As you can see, the code is clearly missing a ending curly brace at the end of the arrow function which causes the error. So how does the code formatting mentioned earlier fit into this? Let’s look at a more real-world example:
In this example, it is a little less clear where the error is. The indentation is not very consistent so you might not notice that the
if statement is actually missing a curly brace after which causes the error.
Fortunately this is pretty simple to fix — you can just add your missing curly brace. In the above example:
It can definitely be challenging to find a missing curly brace. Depending on your code editor of choice, you may be able to configure different colors for each pair of curly brace so it is easier to see which ones match and which ones don’t.
There’s a chance that you received a similarly named but slightly different error:
Unexpected end of JSON input. Rather than simply a missing curly brace, this error often occurs when you are trying to parse a JSON string that is itself missing a curly brace. Here’s an example:
This can be simply fixed by ensuring the string you are parsing is valid JSON if you have control over that string. If you don’t, you can wrap the whole thing in a
try / catch to be safe. Using the previous example:
If you add this to the
parseJson function, you can now handle invalid JSON strings rather than getting an unexpected runtime error.
Hopefully this helps you see how useful good code formatting can be in your code, whether you work with a team or alone. Let us know if you have any other reasons why formatting can be so useful or how you do it in your own code setup. Thanks for reading!