EN
JavaScript - check if function is arrow function
7
points
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