Javascript check function call

How to check if a function exists in JavaScript

An error caused by calling a non-existent function will cause JavaScript to throw an undefined error and stop running your code. To prevent the error, you can first check if a function exists in your current JavaScript environment by using a combination of an if statement and the typeof operator on the function you want to call.

Only when the typeof returns «function» will you call that function to execute it. Let’s look at the following example:

When the type of printMessage is anything other than "function" , you don’t call the function.

Handling non-existent function with try..catch block

Alternatively, you can also use a try..catch block to handle the error when a non-existent function is called:

  Without the try..catch block, the console logs above won’t be executed by JavaScript. You can use the techniques above to check if a JavaScript function exists before calling it.

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

How to Check If a Function Exists in Java Script

Neema Muganga

Neema Muganga Last updated Feb 24, 2022

You’ve probably seen the undefined error in the console when you try to call a function you have not defined in your JavaScript code. JavaScript throws this error and stops running the code.

In this article, I will teach you how to check if a function exists. This way, you can avoid any possible errors. This is a useful technique to see if a specific library or API is available in the client you’re running your software on.

JavaScript has a few different ways to see if a function exists. I’ll show you several.

Use an if Conditional Statement

One way to check if a function is defined is to test it with an if statement. The trick is to test the function as a method of the window object.

So, if you want to test for aFunctionName , just use:

The code in the brackets will execute if the function is defined. If instead you just test the function without using the window object, for example as if(aFunctionName) , JavaScript will throw a ReferenceErorr if the function doesn’t exist.

Let’s consider the following example, which checks for the existence of two functions: one that exists and another that does not exist.

// Testing a function that exists 

Источник

Check if Function Exists Before Calling

When using scripts that are shared between different areas of a site, there may be cases where a function is called that doesn’t exist. It makes sense on one page (the dependency is there) but not another. The difference is too slight to warrant forking the file into different versions. Instead, you can just check if the function exists before calling it to avoid the error:

if (typeof yourFunctionName == 'function')

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

Great snippet! I keep this in my list of common functions and it’s saved me a million times during development. I like to add an ‘else’ statement with an alert (or console.log()) to make the failure more visible.

if (typeof yourFunctionName == 'function') < yourFunctionName(); >else
 // no error checking (yourFunctionName || Function)(); // debugging, maybe on Firefox (yourFunctionName || console.error)(); // debugging on Chrome (yourFunctionName || function()< console.error(arguments) >)(); 
$.isFunction(yourFunctionName)&&yourFunctionName()
yourFunctionName&&yourFunctionName()

The suggestion to check for the type to determine if something exists is questionable. If you’re at the point where you don’t even know a function exists or not and you haven’t designed the situation on purpose, something is very wrong and ill-planned. If you know you have a condition in a game or an asynchronous communication delay, where the user is allowed to check progress or what not, you plan for it and utilize a try-catch. I prefer to use a cautious trigger class to handle this so I can easily define an on event to fire when we need to respond to the alternate code path. You can always check e for the exact error with e.message. You can see that once the classes are defined the actual error handler and function call are terse, while the cautious state handling is set in a reusable class. See the code comments for usage. If you do not define your own onError event, it will fire as a classic alert and not bring down your page.

 cautiousTrigger = function()<>; cautiousTrigger.prototype = < onError : function(e)< alert(e); >, trigger:function(o,func,args) < try < func.apply(o,args); return true; >catch(e) < this.onError(e); >> > someClass = function()<>; someClass.prototype = < yourFunctionName:function(arg1,arg2)< console.log(arg1,arg2); >> var attempt = new cautiousTrigger(); attempt.onError = function(e) < console.log(e.message); doSomethingElse(); >function doSomethingElse() < alert("Hey buddy! Hold your horses, we're doing something awesome."); >var someInstance = new someClass(); // the class instance exists, everything will be fine attempt.trigger(someInstance,someInstance.yourFunctionName,["arg1","arg2"]); //this trigger one will trigger the doSomethingElse function because it doesn't exist yet: attempt.trigger(someOtherInstance,someOtherInstance.yourFunctionName,["arg1","arg2"]); 

If someone wishes to extend an existing object for example add a clamp() or map() function to the Number.prototype object, they could see if someone else has done such a thing using this method. I know many people that like to add those two functions because of how useful they are(including me), and it is trivial to choose this method for determining if someone else has done such a thing. People say not to extend the default objects like this in case they get updated in the future but this method would protect against that issue anyway.

Источник

Check if a JavaScript function is defined.

In this tutorial, I will show you how to check if a JavaScript function is defined or not. This can be useful if you do not want to call a function unless you are 100% sure that it exists.

For example: A particular function exists in an external library and you do not want your code to throw a ReferenceError if that library hasn’t been included properly.

Take a look at the following JavaScript snippet:

//Calling a function that isn't defined. bad_function_call();

In the code above, I am calling a function that doesn’t exist. As a result, the following error will be thrown in the developer console:

Uncaught ReferenceError: bad_function_call is not defined
at file.php:2

The error above is basically telling us that our code has attempted to reference a function that hasn’t been defined. As a result, the rest of our JavaScript code will not be executed.

Check if a JavaScript function exists before calling it.

To check if a particular function name has been defined, you can use JavaScript’s typeof operator:

//Use the typeof operator to check if a JS function exists. if(typeof bad_function_call === «function»)

In our case, the typeof operator will return the string “undefined” because bad_function_call has not been defined. As a result, the function call inside the IF statement will not be executed.

If the function in question does exist, then the typeof operator will return the string “function”:

//Test function. function test() < alert('Hi!'); >//Call the function above if it exists. if(typeof test === «function»)

If you run the JavaScript example above, you will see that an alert box with the string “Hi!” appears.

Catching function ReferenceError errors with a try / catch statement.

Note that another approach is to wrap your function call inside the try block of a try / catch statement like so:

If the function in question does not exist, the error is caught and logged to the console.

Hopefully, you found this guide useful!

Источник

Function.prototype.caller

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Note: In strict mode, accessing caller of a function throws an error — the API is removed with no replacement. This is to prevent code from being able to «walk the stack», which both poses security risks and severely limits the possibility of optimizations like inlining and tail-call optimization. For more explanation, you can read the rationale for the deprecation of arguments.callee .

The caller accessor property of Function instances returns the function that invoked this function. For strict, arrow, async, and generator functions, accessing the caller property throws a TypeError .

Description

If the function f was invoked by the top-level code, the value of f.caller is null ; otherwise it’s the function that called f . If the function that called f is a strict mode function, the value of f.caller is also null .

Note that the only behavior specified by the ECMAScript specification is that Function.prototype has an initial caller accessor that unconditionally throws a TypeError for any get or set request (known as a «poison pill accessor»), and that implementations are not allowed to change this semantic for any function except non-strict plain functions, in which case it must not have the value of a strict mode function. The actual behavior of the caller property, if it’s anything other than throwing an error, is implementation-defined. For example, Chrome defines it as an own data property, while Firefox and Safari extend the initial poison-pill Function.prototype.caller accessor to specially handle this values that are non-strict functions.

(function f()  if (Object.hasOwn(f, "caller"))  console.log( "caller is an own property with descriptor", Object.getOwnPropertyDescriptor(f, "caller"), ); > else  console.log( "f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller", ); console.log( Object.getOwnPropertyDescriptor( Object.getPrototypeOf(f), "caller", ).get.call(f), ); > >)(); // In Chrome: // caller is an own property with descriptor // In Firefox: // f doesn't have an own property named caller. Trying to get f.[[Prototype]].caller // null 

This property replaces the obsolete arguments.caller property of the arguments object.

The special property __caller__ , which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons.

Examples

Checking the value of a function’s caller property

The following code checks the value a function’s caller property.

function myFunc()  if (myFunc.caller === null)  return "The function was called from the top!"; > else  return `This function's caller was $myFunc.caller>`; > > 

Reconstructing the stack and recursion

Note that in case of recursion, you can’t reconstruct the call stack using this property. Consider:

function f(n)  g(n - 1); > function g(n)  if (n > 0)  f(n); > else  stop(); > > f(2); 

At the moment stop() is called the call stack will be:

so if you tried to get the stack trace in the stop() function like this:

let f = stop; let stack = "Stack trace:"; while (f)  stack += `\n$f.name>`; f = f.caller; > 

the loop would never stop.

Strict mode caller

If the caller is a strict mode function, the value of caller is null .

function callerFunc()  calleeFunc(); > function strictCallerFunc()  "use strict"; calleeFunc(); > function calleeFunc()  console.log(calleeFunc.caller); > (function ()  callerFunc(); >)(); // Logs [Function: callerFunc] (function ()  strictCallerFunc(); >)(); // Logs null 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 12, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Читайте также:  Creating bean class in java
Оцените статью