JavaScript Best Practices

Ternary Conditionals

var x = true ? true : false;

 

Nested Ternaries

isArthur && isKing ? (weapon = ‘a, helment = ‘a) : isArcher ? (weapon = ‘b’, helmet = ‘b’) : (weapon = ‘c’, helmet = ‘c’);

 

Logical Assignments

 Var result = 42 || undefined; // 42
 Var result2 = [‘sweet’] || 0 //[‘sweet’,..]
 Var result3 = ‘’ || {object} //{object}

 

If all elements are truthy, then takes the first one:

Var result = ‘king’ || ‘arthur’ // ‘king’

If all elements are falsy, then takes the last one:

Var result = undefined || ‘’ // ‘’

Var result2= ‘’ || undefined // undefined

For && assignments, takes the last truthy value:

Var result = ‘a’ && ‘b’ && ‘c’ // ‘c’

For && if any element is false, short circuits immediately to false:

Var result = false && ‘b’ && ‘c’ // false

 

Switch Statements

Without the break, switch statement has program flow go through each case statement after the first truthy one:

Switch (test) {
 Case false:
 Str = 1
 Case true:
 Str = 2
 Case true:
 Str = 3
}
// str = 3

 

Loop Optimization

Variables defined inside a loop causes CPU processing on each iteration to set the variable, so these should be done outside the loop (if it is legiable)

Var someElement = ‘’;
 for (…) {
 someElement = …
 }

Also, the variable for length is some expensive so these can also be defined before the second definition of the for loop:

for (var i = 0, total = someArray.length; i < total; i++) {
 …
 }