DEV Community

Cover image for Better Syntax Error Messages in JavaScript
Jakub T. Jankiewicz
Jakub T. Jankiewicz

Posted on

Better Syntax Error Messages in JavaScript

Syntax errors can sometimes be intimidating, here I will explain how I created better error messages for my code editor project.

As part of my Koduj project, where I teach JavaScript with a creative coding course, I've created a prototype of a code editor that uses P5.js graphic library.

Normally when you made a syntax error in JavaScript you have a runtime error that doesn't say much about the error itself and you need to ask for help to decipher the error.

An example is this code:

function f(x)
   return 2 * x + 3;
}
Enter fullscreen mode Exit fullscreen mode

That should plot a linear function. I use this example in the second lesson about functions (the first lesson is a lecture about how the computer works).

Normal error from JavaScript looks like this:

Uncaught SyntaxError: Unexpected token 'return'
Enter fullscreen mode Exit fullscreen mode

By an error in my editor look like this:

Unexpected token, expected "{" (2:5)
  1 | function f(x)
> 2 |     return 2 * x + 1;
    |     ^
  3 | }
Enter fullscreen mode Exit fullscreen mode

As you can see the error is obvious now, the missing open curly brace.

So how I did do this? I need to say that it's by accident. I use Prettier to format the code for the user, I do that only when the user presses the button. But luckily I've noticed that Prettier error messages are much better than the ones from the JavaScript parser that I was using (right now I use espree) and of course the JavaScript runtime. So I've added formatting of code on every change user made and saved it in the main state. When the user clicks format I just use what is in the state. But what I now have is much more user-friendly error messages.

If you want to see the playground I've built here is the link:

https://p5.javascript.org.pl/energetic-potential

Note that there are no login and the code use the Firepad editor, Firebase collaborative editor so more than one user can edit the code at once. This is just a prototype, the next version if it will be created will have proper authentication and authorization.

If you like this post you can visit my website and follow me on Twitter @jcubic.

Top comments (2)

Collapse
 
nima_lalaj profile image
yasin cengiz

You, know, can you just make one that is easier for beginners to understand and thank you.

Collapse
 
jcubic profile image
Jakub T. Jankiewicz

If you want something even easier you need to use chatGPT, I've seen people use it to describe the errors.