I'm trying to verify if a function already exists, so I don't create a new function with the same name:
// check if function exists before
alert (typeof window.testfunc) // before creating SHOULD alert "undefined"
function testfunc(){
// do something
}
// check if function exists after
alert (typeof window.testfunc) // after creating the function ok to alert "function"
But it always alerts "function", even when the alert runs before defining the function.
I did try to console.log[window]
before creating the function and it's already in the window object.
What am I missing? How to check if function already exists before creating a new function?
EDIT
Thanks everybody for teaching me about Hoisting! It will be helpful in future coding. This way seems to work (I understand than that Hoisting doesn't apply when there is an if statement)
alert (typeof window.testfunc) // NOW it alerts "undefined"
if (typeof window.testfunc !== "function"){
function testooo(){
}
}
alert (typeof window.testfunc) // ok alerts "function"