Search code examples
javascriptobjecttostringprimitivevalue-of

Object to primitive conversion in Javascript: Please why isn't the valueOf() method called since there is not toString() method


let obj = {
  valueOf() {
    return "2";
  }
};

alert(obj);

I thought in the absence of toString() the valueOf() will be called when a string is expected.


Solution

  • This does not call because this find toString in prototype chain, if we create a object without any prototype it will call

    let obj = Object.create(null)
    
    obj.valueOf =
      function() {
        return "2";
      }
    
    alert(obj);