Doug Leary Doug Leary - 1 month ago 8
Javascript Question

Less than and greater than 10

I'm working on a random code challenge, and I cannot figure out for the life of me how this would be possible

function(obj) {
if ( (obj < 10) && (obj > 10) ) {
return true;
}
}


Things I've tried are setting an interval to change the variable at 0ms(which ends up being browser default), making obj an iife function that increments a global variable every time its' used, and a whole bunch of other seemingly less useful approaches. Any ideas here, or pointers for something obvious i'm missing?

JJJ JJJ
Answer

The clue is in the variable name "obj". When objects are compared, their valueOf() method is called. If we supply a valueOf method that returns a different value every time:

function test(obj) {
   if ( (obj < 10) && (obj > 10) ) {
     return true;
   }
}

var Obj = function() {
  var flag = false;
  
  this.valueOf = function() {
    if( flag ) {
      return 11;
    }

    flag = true;
    return 9;
  }
}

console.log( test( new Obj() ) );

The above object's toValue returns 9 the first time it's called (9 < 10) and 11 from then on (11 > 10).