DEV Community

(a == 1 && a == 2 && a == 3) === true - Wait, hold on...

EmNudge on November 26, 2019

Some of you may recognize the problem in the title. It's a bit of a famous sample of wtfJS, explained very well by Brandon Morelli in 2018. The co...
Collapse
 
notwearingpants profile image
NotWearingPants

There is no reason to use an IIFE, certainly not one that returns anything.
Since we are using a block scoped variable we can just wrap it in curly braces:

{
    let value = 0;
    Object.defineProperty(window, 'a', {
        get() {
            value++;
            console.log("value incremented!");
            return value;
        }
    });
}

if (a === 1 && a === 2 && a === 3) {
    console.log("We got it!");
}
Collapse
 
emnudge profile image
EmNudge

Yes, that's true!
I was thinking more along the lines of having the scope reside entirely within Object.defineProperty where I don't believe a block scope would actually work, which is why I used an IIFE.
But this is completely valid, too!

Collapse
 
emnudge profile image
EmNudge

Haha, that would have been some real weirdness. It still works, but you need some code before it.

I do have a different article, the one on wtfjs and coercion, that is just copy/paste though!