18

Can (a ==1 && a== 2 && a==3) ever evaluate to true in JavaScript?

Comments
  • 5
    let a = true
    😎
  • 2
    @C0D4 nah, I don't think this would work... Because 2 != true (nor does 3)
    πŸ€”πŸ€”πŸ€”

    Or am I wrong?
  • 4
    @kolaente
    Shove it in the console😏

    2 !== true
    But 2 == true
    As 2 is not false.

    If you were using === for comparison, then no you are right it won’t be true.
    however you are not so JS will use falsely comparisons until it can compare.
  • 5
    Rather interesting actually :)
    https://stackoverflow.com/q/...
  • 3
    @C0D4 no, does not work πŸ€”πŸ˜›πŸ˜›
  • 1
    @raldo94 yeeees πŸ˜…
  • 5
    @kolaente you either define a get trap or use the toString method and increment it, each time it's called.
  • 1
    Cant you just

    var i=0
    function a(){
    return i++
    }

    Or something along these lines?
  • 9
    const a = {
    i: 1,
    toString: function () {
    return a.i++;
    }
    }

    if(a == 1 && a == 2 && a == 3) {
    console.log('Hello World!');
    }
  • 0
    Saw this question trending on SO the other day. Apparently was a shitty, gotcha-style interview question.
  • 0
    @koin : stackoverflowed :D
  • 1
    Using "==" instead of "===" in javascript is bad practice. Any code lint will give you an error. It's not "gotcha" interview question if you ever did any real coding besides onclick events in js.
  • 2
    @kargaroth this task is obviously nothing you would do in the real world. It's to figure out if somebody has deep knowledge about the core mechanics of the language.
  • 0
    Why is .toString called when comparing to a number?
  • 1
    @plusgut which are terribly broken. :D
  • 2
    Yes and no. Trying to cast an object to a number, is obviously a bad idea. I agree that the dynamic typing is broken.

    But having the possibility to use the core mechanics, like displaying an object as a string with toString, or having the possibility to define get/set/whatever traps, is a very powerful and great tool.
Add Comment