Reputation: 3465
Consider this code snippet
class A {
constructor() {
this._elem = 5;
}
get elem() {
return this._elem;
}
}
class B {
constructor() {
this._elem = 6;
}
}
class C extends A {
constructor() {
super();
}
}
class D {
constructor() {}
}
const a = new A();
const b = new B();
const c = new C();
const d = new D();
function foo(obj, name) {
const val = 'elem' in obj ? obj.elem : 42;
const val2 = obj.elem ? obj.elem : 42;
console.log(`For ${name} val: ${val}, val2: ${val2}`);
}
foo(a, 'a');
foo(b, 'b');
foo(c, 'c');
foo(d, 'd');
I was trying to figure out if there ever could be a case where directly using obj.elem
when the property elem
doesn't exist on obj
could lead to incorrect logic vis-à-vis doing a check for "elem" in obj
and access it only if it exists and use the value. It seems like val
and val2
would always be the same. Are both equivalent?
Upvotes: 0
Views: 49
Reputation: 351369
No, they are not equivalent, and this is because obj.elem ? obj.elem : 42
will execute the getter and see if its return value is truthy or falsy. If it happens to be falsy, then this expression will evaluate to 42. Yet, "elem" in obj
is true independent on whether the method would return a falsy or truthy value.
Unrelated, but it is also not efficient, as obj.elem ? obj.elem : 42
will execute the getter twice when it returns a truthy value.
Upvotes: 3