Open In App

How to check a function is defined in JavaScript ?

Last Updated : 30 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will check whether a function is defined or not in JavaScript. The JavaScript typeof operator is used to check whether the function is defined or not.

JavaScript typeof Operator

The typeof operator is used to find the type of a JavaScript variable. This operator returns the type of a variable or an expression.

Syntax:

typeof var

Parameters:

It contains a single parameter var which is a JavaScript variable. 

Return value:

It returns the type of a variable or an expression: 

Examples to Check a Function is Defined or Not in JavaScript

Example 1: This example checks the type of the function. If it is a function then it is defined otherwise not defined by using typeof operator

JavaScript
let defined = 'Not defined';

if (typeof fun === 'function') {
    defined = "Defined";
}

console.log("Function " + defined);

Output
Function Not defined

Example 2: This example checks the type of the function, If it is a function then it is defined otherwise not defined by using typeof operator by creating a function. 

JavaScript
function isFunction(possibleFunction) {
    return typeof possibleFunction === 'function';
}

function fun() { }

let defined = 'Not defined';

if (isFunction(fun)) {
    defined = "Defined";
}

console.log("Function " + defined);

Output
Function Defined

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads