Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if function does not exist write function - javascript

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?

like image 342
Bret Thomas Avatar asked Jan 12 '12 17:01

Bret Thomas


People also ask

How do you check JavaScript function exists or not?

Put double exclamation mark i.e !! before the function name that you want to check. If it exists, it will return true.

How do you know if a function exists using the type of operator?

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.

Can we declare function without function keyword in JavaScript?

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 .

Does not exist in JavaScript?

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”.


2 Answers

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)

like image 103
Quentin Avatar answered Oct 18 '22 13:10

Quentin


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.

like image 44
Juank Avatar answered Oct 18 '22 13:10

Juank