Home Other JavaScript Style Guidelines

Using Semicolons

JavaScript often still works if semicolons are omitted, using complex logic called Automatic Semicolon Insertion (ASI). But you should not rely on this and should always insiert semicolons when you end a complete statement of code.

let x = 3
let y = 4
function foo() {

window.onload = function() {
let x = 3;
let y = 4;
function foo() {

window.onload = function() {

Avoid Setting CSS Styles in JavaScript

If you are setting several styles on a DOM object in JS code, instead declare a class in your CSS file and use the JS code to apply that class to the DOM object. This helps keep mmost of the style decisions in your CSS file where they belong and out of your JS code.

// bad (JS)
myButton.style.border = "2px dotted green";
myButton.style.color = "red";
myButton.style.fontSize = "20pt";
myButton.style.fontWeight = "bold";
myButton.style.textDecoration = "underline";
/* good (CSS) */
button.urgent {
  border: 2px dotted green;
  color: red;
  font-size: 20pt;
  font-weight: bold;
  text-decoration: underline;

// good (JS)
myButton.className = "urgent";


We generally don't cover exceptions in JavaScript in this course. So, in general, you should avoid try/catch statements because this is not how we intend you to solve the problems. But if you do need to use one, don't ever catch an exception with an empty catch block.

try {
} catch (npe) {}