Bite-sized screencasts for React
and frontend developers

How to check if a function already exists in Javascript

posted on: 05-jul-2018

I've received a question from a reader whose background is in PHP. The other day he asked me if there was a JavaScript equivalent of PHP’s function_exists() method.

For example, when building a plugin that extends some existing code in PHP, it’s a good practice to make sure that plugin (and the required function from it) exists before running your code.

if (function_exists('get_purchases')) {
	$purchases = get_purchases(123);
}

Given how fragile JavaScript is, this isn’t a bad idea, either. Here’s how you would do something similar with vanilla JS.

For simplicity, let’s say we want to use a JS method called getPurchases(). You would use typeof to check if the method you want to use is a function.

if (typeof getPurchases === 'function') {
	getPurchases(123);
}

If the method was scoped to a namespaced plugin (for example, checkout.getPurchases(), it’s also a good idea to make sure that the namespace exists, too.

if (checkout && typeof checkout.getPurchases === 'function') {
	checkout.getPurchases(123);
}

Here’s a simple helper method you can use if you find yourself needing to do this a lot.

const functionExists = function (method, scope) {
	if (scope) {
		const namespace = window[scope];
		return (namespace ? true : false) && typeof namespace[method] === 'function';
	}
	return typeof window[method] === 'function';
};

if (functionExists('getPurchases', 'checkout')) {
	getPurchases(123);
}

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.