In php I'm writing the following
<?php
if(x != 0) {
echo "function myfunction(){};";
}
?>
In javascript I wish to test if the function exists and if not write out an empty function
if(typeof myfunction != 'function'){
function myfunction(){};
}
This works great in firefox but, in chrome even if the typeof equals function it still goes into and creates the empty function. I can't find a work around for chrome, i've tried if(!myfunction), if(typeof window.myfunction != 'function) but nothing seems to work here for chrome when everything seems to work in firefox. Any ideas?
Put double exclamation mark i.e !! before the function name that you want to check. If it exists, it will return true.
Using instanceof operator: The instanceof operator checks the type of an object at run time. It return a corresponding boolean value, i.e, either true or false to indicate if the object is of a particular type or not. Example: This example uses instanceof operator to check a variable is of function type or not.
Conclusion. We can do without the function keyword in today's JavaScript code. We can use arrow functions for functions that don't need to reference this and use the method shorthand for anything that needs to reference this .
The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.
Use a function expression, not a function declaration.
if(typeof myfunction != 'function'){
window.myfunction = function(){};
}
(I'm using window
since your last paragraph suggests you want a global function)
You should use strict comparison operator !==
if(typeof myFunction !== 'function'){
window.myFunction = function(){}; // for a global function or
NAMESPACE.myFunction = function(){}; // for a function in NAMESPACE
}
Also try to keep js functions inside namespaces, this way you avoid collisions with other js libraries in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With