Skip to content Skip to sidebar Skip to footer

How To Programmatically Distinguish An Arrow Function From A Regular Function?

There is no obvious difference between an arrow function and a regular function. ({}).toString.call(function () {}) '[object Function]' ({}).toString.call(() => {}) '[object Fun

Solution 1:

The best I can think of is using toString:

let isArrowFunction;

isArrowFunction = (fn) => {
    console.log(fn.toString());

    return fn.toString().indexOf('function') !== 0;
};

console.log(isArrowFunction(() => {}) === true);
console.log(isArrowFunction((foo: string) => {}) === true);
console.log(isArrowFunction(function () {}) === false);

See:

(function () {}).toString();
"function () {}"

(() => {}).toString();
"() => {}"

Solution 2:

Uhm, the requirements are a bit weird, but I made some tests and:

typeof (() => {}).prototype === "undefined"

Is true, while:

typeof (function () {}).prototype === "undefined"

Is false, so:

functionisArrow(x)
{
  returntypeof (x.prototype) === "undefined"
}

Fiddle here: https://jsfiddle.net/87kn67ov/

Post a Comment for "How To Programmatically Distinguish An Arrow Function From A Regular Function?"