INF310: Modern JS, Fall 2017 > Language Features > Conditionals
Conditionals
comparators

Style guide: use strict comparisons

  a == b;
  a === b;

  a != b;
  a !== b;

  a > b;
  a >= b;

  a < b;
  a <= b;

  // there are no strict versions of > and <
logical operators
  // logical operators return values (not Booleans)
  a && b; // logical AND; short circuit
  a || b; // logical OR; short circuit

  // use AND to guard against null / undefined
  doSomething(myObject && myObject.myProperty);
  myObject && myObject.doSomething && myObject.doSomething();

  // use OR to set a default value
  sumNumbers(numbers || []);
  (myObject || defaultObject).doSomething();
False-y values
  • false
  • undefined
  • null
  • 0
  • NaN
  • "" empty string
if
  if (condition) {

  // the following "else" forms are equivalent
  } else {
    if (check) {

    } else if (fallback) {

    }
  }
ternary
  const result = condition ? resultIfTrue : resultIfFalse;
switch
  switch (condition) {
    case value1:
      doStuff();
      break;
    case value2:
      doOtherStuff();
      evenMoreStuff();
      break;
    default:
      doDefaultStuff();
  }
Pattern matching proposal
  match (expression) {
    [a, b, ...c]: useArray(a, b, c)
    { name, age }: useObject(name, age)
    else: { throw new Error(); }
  }
Links