Search code examples
javascriptundefinednull-coalescing

Operating on undefined variable - null coalescing


function add(num) { 
  var sum;
  for (var i = 1; i < num + 1; i++){
    sum = (sum || 0) + i;
  }; 
  return sum;     
}
add(9);

What is a keyword to describe the behavior for defining sum when it gets added to "i" in the for loop? Is this a ternary operation? Obviously the first time it loops through it is undefined, so javascript chooses 0. Why is that?


Solution

  • The "or" operator || works like this:

    • If the first operand is "truthy," the first operand is returned.
    • Otherwise, the second operand is returned.

    Since undefined is not truthy, sum || 0 is zero the first time through the loop.

    I don't know that there's a specific term for this behavior. * It's simply a convenient way to initialize a variable which may not have been pre-initialized. In your example, it would make more sense to initialize the variable at the start:

    function add(num) { 
      var sum = 0;
      for (var i = 1; i < num + 1; i++){
        sum += i;
      }; 
      return sum;     
    }
    


    Note that this has nothing to do with the conditional (ternary) operator:

    condition ? expr1 : expr2 
    


    * With credit to @joews, there is a term for this behavior: "null coalescing"

    But note his caveat:

    It's a common logic bug to use this pattern where the first operand could legitimately be falsy. Never use var a = b || c where, say, 0 is a valid value for b.