JavaScript: Conditions & Loops

Conditions & Testing

  • 0, NaN, undefined, null and empty string can all be taken as false
  • Everything else taken as true
  • Unpredictable and care should be taken to avoid misunderstandings
  • Use === & !==, strict (in)equality. Compares object references.
  • Loose (in)equality (== & !=) not predictable due to unexpected type conversions
  • Number.isNaN(myVar) should be used for checking if NaN (myVar===NaN always false)
  • myVar==null checks for null and undefined
  • Ensure both operands are boolean when using && and || otherwise one or other operand will be returned (zero and empty strings can unexpectedly be taken as false)

Loops

for(let j = 0; j < 10 ; j++)loops 10 times from 0 to 9
(initialise; end condition; action at end of each iteration)
for(const nextValue of theArray)loops at the values in an array (objects are not iterable)
for(const [index, elem] of theArray.entries())loops at the values in an array (objects are not iterable)
for(const nextKey in theObj)loops at the keys in an object/array
(always a string for arrays, so nextKey + 1 → “2” + 1 → “21”).
while(condition is true){ … }Only enters loop if condition is true
do{….} while(condition is true)Always performs first iteration
  • Break: leaves a loop
  • Continue: ends the current iteration and starts the next, remains in the loop.

Consider theArray.keys() and theArray.values() in addition to theArray.entries().

Switch

Uses strict equality to compare the condition. That is the first case is invoked if “TheCondition===1”

switch (theCondition){
case 1:
	….do things here if theCondition is 1
	break;
case 2:
case 3:
	….do other things here if theCondition is 2 or 3
	break;
default:
	….fallback for all other values
}

As with the switch statement in other languages, once a valid case value has been found execution continues until the next break statement.

Try/Catch

try{
	... do stuff ...
	throw “oops..”  // or throw Error(myErrorText)
}catch(err){
	console.log(err)
}finally{
	// release any resources here
}