false == 'false' // false
false == '' // true
false === '' // false
var x = false || 'foo' // x is 'foo'
var y = true || 'foo' // y is true
var z = y && x // z is 'foo'
Your data structures shouldn't usually be capable of being T | null | undefined, so I'd argue there's really no place for double equals in a modern codebase.
Coercion leads to an unpredictability and that means that the uncertainity is high therefore there's a risk for code to be erroneous. A risk that should usually be avoided by the language itself.
In simpler situations it might be okay-ish but in large codebases, with other things that contend to the unpredictable nature of Javascript, it does get messy and difficult and this holds specially true for data structures!
undefined representing not having attempted to retrieve data yet and null representing no data is a bit vague and implicit; unless there was a comment outlining this, do you think it would be obvious when reading the code that this was your intent?
Personally I'd opt for null to represent no or empty data and a second variable or property to represent how you have or have not attempted to retrieve said data, probably written as an enum for maximum clarity.
// This really needs commenting to make clear what each falsy value represents
let data: Data | null | undefined = undefined;
// This is much clearer IMO
enum DataFetchState {
Success,
Failure,
InProgress,
None,
}
let state: DataFetchState = DataFetchState.None;
let data: Data | null = null;
I didn't mean "no data yet" as in "no data from database". I meant not initialized variable/property. It should be undefined since it's not yet, well, defined.
The other cases should be null.
That's what I use, my company uses and I've seen it used often.
28
u/DerGernTod May 28 '19
coercion in general