乐闻世界logo
搜索文章和话题

Check if a variable is of function type

1个答案

1

In JavaScript, to check if a variable is a function, we typically use the typeof operator. For functions, typeof returns the string "function". This is a straightforward and general method that ensures the variable is indeed a function. Here is an example:

javascript
function exampleFunction() { console.log("Hello, World!"); } var notAFunction = "I am a string"; // Check if exampleFunction is a function if (typeof exampleFunction === "function") { console.log("exampleFunction is a function"); } else { console.log("exampleFunction is not a function"); } // Check if notAFunction is a function if (typeof notAFunction === "function") { console.log("notAFunction is a function"); } else { console.log("notAFunction is not a function"); }

In this example, exampleFunction is correctly identified as a function, while notAFunction is not. This approach is highly suitable for determining at runtime whether any given variable can be called as a function, thereby avoiding runtime errors.

2024年6月29日 12:07 回复

你的答案