Home Variables

Variable Scope

Declare variables in the narrowest possible scope. For example, if a variable is used only inside a specific if statement, declare it inside that if statement rather than at the top of the function or the top of the JavaScript file/class.

Constants

If a particular constant value is used frequently in your code, declare it as a module-global "constant" variable in uppercase, and always refer to the constant in the rest of your code rather than the corresponding value.

let ALPHABET_LENGTH = 26;

Saving Expensive Calls Into Variables

If you are calling an expensive function and using its result multiple times, save that reuslt in a variable rather than having to call the function multiple times.

if (list.indexOf("abc") >= 0) {
  list.remove(list.indexOf("abc"));
}
let index = list.indexOf("abc");
if (index >= 0) {
  list.remove(index);
}