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?
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?
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 [].