Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing undefined parameter to function - check if variable exists [duplicate]

Tags:

javascript

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.

like image 864
cronoklee Avatar asked Jun 05 '13 14:06

cronoklee


3 Answers

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.

like image 105
Buh Buh Avatar answered Oct 19 '22 14:10

Buh Buh


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.

like image 33
RichieHindle Avatar answered Oct 19 '22 15:10

RichieHindle


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.

like image 31
Brad M Avatar answered Oct 19 '22 15:10

Brad M