Languages
[Edit]
EN

JavaScript - check if function is arrow function

7 points
Created by:
ArcadeParade
666

In this short article, we would like to show how to check if function is arrow function in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const isArrowFunction = (variable) => {
  	if (typeof variable=== 'function') {
        const source = variable.toString();
        return /^\([^)]*\)\s*=>/.test(source);
    }
  	return false;
};


// Usage example:

console.log(isArrowFunction(() => {}));                  // true
console.log(isArrowFunction((arg1, arg2, arg3) => {}));  // true

console.log(isArrowFunction(function() {}));             // false
console.log(isArrowFunction(function action() {}));      // false

Warning: be careful, some transpilers may convert functions types depending on target (ES3, ES5, ES6, etc.).

 

Alternative solution

// ONLINE-RUNNER:browser;

const isArrowFunction = (variable) => {
    if (typeof variable === 'function') {
        return !variable.prototype;
    }
    return false;
};


// Usage example:

console.log(isArrowFunction(() => {}));                  // true
console.log(isArrowFunction((arg1, arg2, arg3) => {}));  // true

console.log(isArrowFunction(function() {}));             // false
console.log(isArrowFunction(function action() {}));      // false

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join