MENU
Test Yourself!
Can (a== 1 && a ==2 && a==3) ever evaluate to true? How many ways can you think of to make the expression true?
0 way: Have you read this chapter?
1 way: Would you like to re-read this chapter?
2 ways: You should have read this chapter.
3 ways: You must have read this chapter.
4 ways: Experienced JavaScript Expert!
5 ways: Seasoned JavaScript Veteran!
6 ways: JavaScript Master!
7 ways: JavaScript Grandmaster!
8 ways: JavaScript King!
9 ways: JavaScript God!
Here are 9 ways:
let a = {
i: 1,
toString: function () {
return a.i++;
}
};
if (a == 1 && a == 2 && a == 3) console.log('possible 1');var a = [1, 2, 3];
a.join = a.shift;
if (a == 1 && a == 2 && a == 3) console.log('possible 2');let i = 0;
let a = { [Symbol.toPrimitive]: () => ++i };
if (a == 1 && a == 2 && a == 3) console.log('possible 3');class Thing {
constructor() {
this.value = 1;
}
valueOf() {
return this.value++;
}
}
Var a = new Thing();
if (a == 1 && a == 2 && a == 3) console.log('possible 4');var i = 0;
with ({
get a() {
return ++i;
}
}) {
if (a == 1 && a == 2 && a == 3) console.log('possible 5');
}var a = new Proxy({ i: 0 }, {
get: (target, name) => name === Symbol.toPrimitive ? () => ++target.i : target[name],
});
if (a == 1 && a == 2 && a == 3) console.log('possible 6');const value = function* () {
let i = 0;
while (true) yield ++i;
}();
Object.defineProperty(this, 'a', {
get() {
return value.next().value;
}
});
if (a == 1 && a == 2 && a == 3) console.log('possible 7');var a = { valueOf: () => this.n = (this.n || 0) % 3 + 1 };
if (a == 1 && a == 2 && a == 3) console.log('possible 8');var i = 0;
Object.defineProperty(window, 'a', {
get: function () {
return ++val;
}
});
if (a == 1 && a == 2 && a == 3) console.log('possible 9');(Courtesy of https://stackoverflow.com/questions/48270127/ can-a-1-a-2-a-3-ever-evaluate-to-true)
“Honestly though, whether there is a way for it to evaluate to true or not (and as others have shown, there are multiple ways), the answer I'd be looking for, speaking as someone who has conducted hundreds of interviews, would be something along the lines of:
--- Frank W. Zammetti (StackOverflow member)