JavaScript Best Practices

Conditionals


General purpose looping

When loops are required, feel free to choose an appropriate loop out of the available ones (forfor...ofwhile, etc.) Just make sure to keep the code as understandable as possible.

When using for/for...of loops, make sure to define the initializer properly, with a let keyword:

let cats = ['Athena', 'Luna'];
for(let i of cats) {
  console.log(i);
}

Not

let cats = ['Athena', 'Luna'];
for(i of cats) {
  console.log(i);
}

Also bear in mind:

  • There should be no space between a loop keyword and its opening parenthesis.
  • There should be a space between the parentheses and the opening curly brace.

Switch statements

Format switch statements like this:

let expr = 'Papayas';
switch(expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    // expected output: "Mangoes and papayas are $2.79 a pound."
    break;
  default:
    console.log(`Sorry, we are out of ${expr}`);
}