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:
xxxxxxxxxx
1
const isArrowFunction = (variable) => {
2
if (typeof variable=== 'function') {
3
const source = variable.toString();
4
return /^\([^)]*\)\s*=>/.test(source);
5
}
6
return false;
7
};
8
9
10
// Usage example:
11
12
console.log(isArrowFunction(() => {})); // true
13
console.log(isArrowFunction((arg1, arg2, arg3) => {})); // true
14
15
console.log(isArrowFunction(function() {})); // false
16
console.log(isArrowFunction(function action() {})); // false
Warning: be careful, some transpilers may convert functions types depending on target (ES3, ES5, ES6, etc.).
xxxxxxxxxx
1
const isArrowFunction = (variable) => {
2
if (typeof variable === 'function') {
3
return !variable.prototype;
4
}
5
return false;
6
};
7
8
9
// Usage example:
10
11
console.log(isArrowFunction(() => {})); // true
12
console.log(isArrowFunction((arg1, arg2, arg3) => {})); // true
13
14
console.log(isArrowFunction(function() {})); // false
15
console.log(isArrowFunction(function action() {})); // false