To check function is not defined, call the typeof
operator and pass the function name. If the function is not defined, the typeof
operator will return "undefined"
and does not generate an error.
function func(){ console.log('Hello World!'); } if(typeof func === 'undefined'){ console.log('Function is not defined.'); }else{ //else block runs console.log('Function is defined.') }
The typeof operator returns a string that tells you the type of value stored in a variable.
console.log(typeof function(){}); //"function" console.log(typeof (()=>{})); //"function" console.log(typeof [1,2,3,4,5]); //"object" console.log(typeof 123); //"number" console.log(typeof "JavaScript"); //"string"
If a variable is not defined then the typeof
operator returns "undefined"
.
console.log(typeof variableDoesNotExist); //"undefined"
When you write a function using function declaration then that function gets hoisted to the top of the script or scope. If you use the typeof
operator before the function declaration, the typeof
operator will return "function"
not "undefined"
.
if(typeof func === 'function'){ //if block runs console.log('Function is defined.'); }else{ console.log('Function is not defined.') } function func(){ console.log('Hello World!'); }
Output
Function is defined.
If you declare a function with the let
or const
keyword and use the typeof operator before the function expression, you would get an error.
//ReferenceError: Cannot access 'func1' before initialization if(typeof func1 === 'function'){ console.log('Function func1 is defined.'); }else{ console.log('Function func1 is not defined.') } let func1 = function(){ console.log('Function func2()'); }
However, if you declare the function with the var
keyword, you won't get an error because the function gets hoisted.
if(typeof func1 === 'function'){ console.log('Function func1 is defined.'); }else{ //else block runs console.log('Function func1 is not defined.') } var func1 = function(){ console.log('Function func2()'); }
Output
Function func1 is not defined.
Still, the typeof
operator returns undefined
because the following would happen behind the scene.
var func1; if(typeof func1 === 'function'){ console.log('Function func1 is defined.'); }else{ //else block runs console.log('Function func1 is not defined.') } func1 = function(){ console.log('Function func2()'); }