In JavaScript, the typeof keyword can be used to check if a variable is a function, which will always return "function".
Abstract
The article explains how to check if a variable is a function in JavaScript using the typeof keyword. It clarifies that JavaScript functions can be invoked using the function or class keywords or created anonymously using arrow functions. Functions can be assigned to variables and passed around to functions like any other JavaScript data type, which is often referred to as a callback function. The article also provides examples of how to check if a function is assigned to a variable or named using the function or class keywords.
Bullet points
JavaScript functions can be invoked using the function or class keywords or created anonymously using arrow functions.
Functions can be assigned to variables and passed around to functions like any other JavaScript data type.
The typeof keyword can be used to check if a variable is a function, which will always return "function".
If the function is assigned to a variable, check typeof the name of that variable, whether it was invoked using let, var, or const.
If the function was named using the function or class keywords but not assigned to a variable, then check typeof the function’s given name.
Passing functions as variables to other functions is very common in JavaScript, and the term "callback function" refers to this practice.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
Callbacks are used in modern web APIs, often with asynchronous promises.
How to Check for a Function in JavaScript
Want to know if a variable is a function in JavaScript? Simply use typeof — variables containing functions will always return "function".
New programmers to JavaScript are often not familiar with the idea that a function can be stored in a variable, just like any primitive type.
A function stored in a variable is often called a callback function, at least when that function is being passed into another function as a parameter.
“A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.” — MDN Docs