Search code examples
javascriptfunctiontype-conversionprimitive

Javascript [Symbol.toPrimitive](hint) to convert function


In JS functions belong to the object type. Objects can be converted to primitive types with [Symbol.toPrimitive](hint). This pure-object conversion works fine:

let obj = {
  [Symbol.toPrimitive](hint) {
    switch(hint) {
      case "string": return "all right";
      case "number": return 100;
      default: return "something else";
    }
  }
};

alert(obj); // all right
alert(+obj); // 100

However, something is wrong with function conversion:

function fun() {
  [Symbol.toPrimitive](hint) { // JS engine starts to complain here
    switch(hint) {
      case "string": return "all right";
      case "number": return 100;
      default: return "something else";
    }
  }
}

alert(fun);
alert(+fun);

What am I missing here? How do I convert function to some primitive type?


Solution

  • You need to address the function's Symbol.toPrimitive property and assign a function.

    Otherwise you take an array with a symbol and try to call a function with it, which not exists.

    function fun() {
    }
    
    fun[Symbol.toPrimitive] = function (hint) {
        switch(hint) {
            case "string": return "all right";
            case "number": return 100;
            default: return "something else";
        }
    };
    
    console.log(fun);
    console.log(+fun);