-5

I'm looking at this Javascript class:

'use strict';
class Account {
  constructor(a, b, c) {
    this.a = a
    this.b = b || []
    this.c = c || []
  }
}

What is b || [] saying?

Kelvin Lau
  • 6,373
  • 6
  • 34
  • 57
  • if be b can be evaluated to false it will return [], otherwise it returns b – CoderPi Jan 13 '16 at 19:53
  • http://stackoverflow.com/questions/4576867/javascript-or-operator-with-a-undefinded-variable – epascarello Jan 13 '16 at 19:55
  • you can use it as a default initializer if the left side var is (falsy) wich means, that holds a 0, false, undefined... the value from the right side of the || will be used, in this case, an empty array will be assigned to the var – rmjoia Jan 13 '16 at 19:55

1 Answers1

1

The || operator returns the first truth-y value that it sees. Many people will use this as a shortcut to set default values for variables as undefined is false-y. The issue in doing so is that the default will also be used for null, false, 0, NaN, and empty strings (all of which may or may not actually be valid values).

In this case, if b or c is undefined (or any other false-y value), this.b and this.c will be set to [].

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536