JavaScript Best Practices
We've covered several introductory concepts for JavaScript programming in this course and how to debug your code. We'll review some coding guidelines and best practices you'll use as a JavaScript developer to ensure consistency, readability, security, and accessibility. Read this article to learn about some of the best practices for developing programs.
Conditionals
General purpose looping
When loops are required, feel free to choose an appropriate loop out of the available ones (for
, for...of
, while
, 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}`); }