Javascript define function if defined

Javascript define function if defined

Last updated: Jan 6, 2023
Reading time · 4 min

banner

# Check if a Function is Defined in JavaScript

Use the typeof operator to check if a function is defined.

The typeof operator returns a string that indicates the type of a value. If the function is not defined, the typeof operator returns «undefined» and doesn’t throw an error.

Copied!
function greet() return 'hello world'; > if (typeof greet === 'function') // 👇️ this runs console.log('✅ function is defined'); console.log(greet()); // 👉️ hello world > else console.log('⛔️ function is NOT defined'); >

We used the typeof operator to check if a function is defined.

The operator returns a string that indicates the type of a value. Here are some examples:

Copied!
console.log(typeof (() => >)); // 👉️ "function" console.log(typeof function () >); // 👉️ "function" console.log(typeof null); // 👉️ "object" console.log(typeof []); // 👉️ "object" console.log(typeof >); // 👉️ "object" console.log(typeof ''); // 👉️ "string" console.log(typeof 0); // 👉️ "number"

The typeof operator doesn’t throw an error when used with a variable that is not declared, instead, it returns the string «undefined» .

Copied!
console.log(typeof doesNotExist); // 👉️ "undefined"

However, if you use the typeof operator before declaring a variable with the let or const keywords, you would get an error.

Copied!
// ⛔️ ReferenceError: Cannot access 'myFunction' before initialization if (typeof myFunction === 'function') console.log('✅ function is defined'); > else console.log('⛔️ function is NOT defined'); > const myFunction = () => >;

We used the typeof operator before initializing a function using the const keyword.

This causes an error because we are trying to access a variable that exists in the program, but is not yet declared.

We would get the same result if we declared the function using the let keyword.

However, if we use the var keyword, we wouldn’t get an error because of how hoisting works in JavaScript.

Copied!
if (typeof myFunction === 'function') console.log('✅ function is defined'); > else // 👇️ This runs console.log('⛔️ function is NOT defined'); > var myFunction = () => >;

We declared the function using the var keyword, so we didn’t get an error when using the typeof operator, however, the else block ran.

This is what happens under the hood when using the var keyword.

Copied!
var myFunction; if (typeof myFunction === 'function') console.log('✅ function is defined'); > else // 👇️ This runs console.log('⛔️ function is NOT defined'); > myFunction = () => >;

The declaration of the variable gets hoisted to the top, however, the assignment of the value remains where it is.

Named functions get hoisted to the top, so you can call a named function even before the line on which it is declared.

Copied!
if (typeof greet === 'function') // 👇️ this runs console.log('✅ function is defined'); console.log(greet()); // 👉️ hello world > else console.log('⛔️ function is NOT defined'); > function greet() return 'hello world'; >

You can imagine that the declaration of the greet() function got moved to line 1.

When the if statement runs, the function is available in the scope and can be called.

Note that only named functions (ones that use the function keyword) get hoisted to the top of the file.

# Check if a Function is Defined using a try/catch block

This is a three-step process:

  1. Call the function in a try/catch statement.
  2. If the function is defined, the try block will run successfully.
  3. Otherwise, the catch block will run.
Copied!
try const result = greet(); console.log(result); // 👉️ hello world > catch (err) console.log('The function is not defined'); > function greet() return 'hello world'; >

We called the function in a try/catch block.

The function is defined and available in the scope, so the try block completed.

If the function is not defined, the catch block runs.

Copied!
try const result = greet(); console.log(result); > catch (err) // 👇️ this runs console.log('The function is not defined'); >

We tried to call a function that doesn’t exist in the scope, so the error got passed to the catch block.

The catch block handles the error, so your program won’t crash due to an unhandled error.

# Check if a Variable is of type Function using instanceof

You can also use the instanceof operator to check if a variable is a function.

The instanceof operator will return true if the variable is of type function and false otherwise.

Copied!
function sum(a, b) return a + b; > if (sum instanceof Function) // 👇️ this runs console.log('✅ The variable is of type function'); > else console.log('⛔️ The variable is NOT of type function'); >

The syntax for the instanceof operator is object instanceof constructor .

The operator returns true if the prototype property of the constructor appears anywhere in the prototype chain of the object.

One thing to note about the instanceof operator is that it won’t work as expected if you’re checking a function that is from another document, e.g. an iframe.

Each document will have its own Function object, so the instanceof check should not be used in this scenario.

The typeof operator would work as expected even if the function comes from a different document (e.g. an iframe).

# Check if a Variable is of type Function using string comparison

You can also convert a value to a string to check if it is a function.

Copied!
function isTypeFunction(f) const functionTypes = ['[object Function]', '[object AsyncFunction]']; return functionTypes.includes(Object.prototype.toString.call(f)); > // ✅ synchronous function function subtract(a, b) return a - b; > // ✅ asynchronous function async function sum(a, b) return a + b; > console.log(isTypeFunction(sum)); // 👉️ true console.log(isTypeFunction(subtract)); // 👉️ true console.log(isTypeFunction('abc')); // 👉️ false

We used the toString() method to convert the passed-in value to a string and compared the output to the result of calling the method with a function.

Copied!
// ✅ for sync functions function subtract(a, b) return a - b; > // 👇️ "[object Function]" console.log(Object.prototype.toString.call(subtract)); // -------------------------------------------------- // ✅ for async functions async function sum(a, b) return a + b; > // 👇️ "[object AsyncFunction]" console.log(Object.prototype.toString.call(sum));

Converting a synchronous function to a string returns » [object Function] «, whereas converting an async function to a string returns » [object AsyncFunction] «.

This code sample is for demonstration purposes only as there is no good reason to use this approach.

Using the typeof operator should be your preferred approach as it is the most performant, readable and works between different contexts (e.g. in iframes).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Html css музыкальный плеер
Оцените статью