I create functions in Javascript dynamically. Sometimes I need to check if a certain function is actually already created.
I have the name of the function as a string. How can I check whether a function exists based on a given value in a string?
Please, some explanation. In two cases, simply call function_exists with the name of function parameter to check existence, returns bool.
You could directly execute it with eval() such as eval(functionName + "()") or you could get a reference to the function with eval("let fn = " + functionName) and then use the newly defined fn variable to call the function.
Use the typeof operator to check if a method exists in a class, e.g. if (typeof myInstance. myMethod === 'function') {} . The typeof operator returns a string that indicates the type of the specific value and will return function if the method exists in the class.
You can check whether it's defined in the global scope using;
if (typeof window[strOfFunction] === "function") { // celebrate //window[strOfFunction](); //To call the function dynamically! }
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