Open In App

How to check a function is defined in JavaScript ?

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

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. 

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
Article Tags :