JavaScript Best Practices

Variables


Variable naming

For variable names use lowerCamelCasing, and use concise, human-readable, semantic names where appropriate.

Do this:

let playerScore = 0;

let speed = distance / time;

Not this:

let thisIsaveryLONGVariableThatRecordsPlayerscore345654 = 0;

let s = d/t;

Note: The only place where it is OK to not use human-readable semantic names is where a very common recognized convention exists, such as using ij, etc. for loop iterators.


Declaring variables

When declaring variables and constants, use the let and const keywords, not  var.

If a variable will not be reassigned, prefer const:

const myName = 'Chris';
console.log(myName);

Otherwise, use let:

let myAge = '40';
myAge++;
console.log('Happy birthday!');

This example uses let where it should prefer const. It will work but should be avoided in MDN code examples:

let myName = 'Chris';
console.log(myName);

This example uses const for a variable that gets reassigned. The reassignment will throw an error:

const myAge = '40';
myAge++;
console.log('Happy birthday!');

This example uses var, which should be avoided in MDN code examples unless it is really needed:

var myAge = '40';
var myName = 'Chris';