Skip to main content

Overview


  • Why do semi-colons exist in JavaScript?
  • Why we left this topic until this late in the course
  • Whether or not we recommend using semi-colons
  • When using semi-colons, when should you put them in and when you shouldn't

Answers: Minification - removes all the comments, blank spaces, any parts of the code that isn't needed. Don't minify your code yourself, let something else minify it. Tools such as webpack, parcel, or vite can be used to parse and minify your code.

Use semicolons if you want to, or if you don't.

Prettier


Use Prettier (steps linked here) to format your code before you publish it.

ESLint


Use ESLint to check your syntax

What I have


I use Prettier-ESLint extension in VS Code. I don't need to add semicolons if I don't. As soon as I save the file, semicolons appear. I could type in the most garbage formatted code ever and it will format as soon as I save for format. Example:

console.log("Step 1"); try {  nonExistentFunction()} catch (error) {
console.error(`The error be: ${error}`) // Uncaught ReferenceError: nonExistentFunction is not defined
}console.log ("Step 2")

//formats into
console.log("Step 1");
try {
nonExistentFunction();
} catch (error) {
console.error(`The error be: ${error}`); // Uncaught ReferenceError: nonExistentFunction is not defined
}
console.log("Step 2");

Automatic Semi-colon Insertion


MDN Docs

Here are the most common statements where ASI applies:

  • let/const variable declarations.
  • import/export statements.
  • return.

Watch how you use JSX - which is not either Javascript or HTML:

function App() {
return ; // (similar to return undefined if you allow it to use automatic semicolon insertion)
<div>
Hello
</div>
}

Chapter Recap


  • JavaScript has semi-colons because it's common to minify the code before publishing the website.
  • Automated tools will minify your code. You should never minify it yourself or write minified code.
  • Minification works by removing the comments and removing all the blank spaces (thus putting all your code on 1 line).
  • You can decide to use semi-colons or not based on your own preference.
  • If/when you work at a company, you will be instructed to use semi-colons or not based on the team's preferences.
  • Tools (such as prettier) can automatically insert semi-colons in your source code.
  • Code style is the set of rules and guidelines that a certain team/person/company uses while developing a project.
  • The most popular tool for enforcing/recommending certain code styles in JavaScript is called ESLint.
  • Some specific statements in JavaScript need to end with a semi-colon. So, if the programmer left them out, the JavaScript engine will automatically place a semi-colon. This is called Automatic Semi-colon Insert and only applies in very specific cases.