Consider the following Javascript:
function getType(obj){
return(typeof(obj))
}
alert(typeof(obj)) //alerts "undefined" correctly
alert(getType(obj)) //throws an error: ReferenceError: obj is not defined
Why might this be happening? Is there any workaround? I am trying to write a function which checks if a variable exists.
The problem is nothing to do with typeof. The problem is that you cant pass undefined variables to functions.
function doNothing(obj){
}
doNothing(obj);
This code too results in the error: Uncaught ReferenceError: obj is not defined
So it doesn't matter what code you write inside your function, as it won't be called. The error happens before the function call.
typeof
is an operator, not a function.
This is why it does not behave in the same way as functions.
typeof
is an operator, not a function, and therefore has powers that a function can't have. There's no way to do what you're trying to do.
Your function fails as soon as you try to pass an undefined object. You can't encapsulate the typeof()
function. Well, you can, but it will always throw errors when passed undefined objects.
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