Skip to content
the poor coder

check if it is a function javascript

Poor Man
Published
Reading time
1 min read
On this page

How to check if it is a function in JavaScript#

If you are a JavaScript developer, it is essential to know how to identify whether a variable is a function or not. There are various ways to check if a variable is a function, and we will discuss some of them here.

Using the typeof operator#

The easiest and most common way to check if a variable is a function is by using the typeof operator. It returns the type of the operand, and if the operand is a function, it will return "function". Here is an example:

Text

function myFunction() {
  console.log("Hello World!");
}

console.log(typeof myFunction); // Output: "function"

Using the instanceof operator#

You can also use the instanceof operator to check if a variable is a function. It checks if an object is an instance of a particular class, and since functions are objects in JavaScript, you can use this operator to check if a variable is a function. Here is an example:

Text

function myFunction() {
  console.log("Hello World!");
}

console.log(myFunction instanceof Function); // Output: true

Using the Object.prototype.toString() method#

The Object.prototype.toString() method returns the type of an object as a string. You can use this method to check if a variable is a function by calling it on the variable and checking if the returned string contains the word "function". Here is an example:

Text

function myFunction() {
  console.log("Hello World!");
}

console.log(Object.prototype.toString.call(myFunction)); // Output: "[object Function]"

These are some of the most common ways to check if a variable is a function in JavaScript. Remember that functions are objects in JavaScript, so you can use any method that checks if a variable is an object to check if it is a function.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC