1

I have created a function to get type information about a variable. The function works very well except for one case. If I pass an undefined variable the browser does not execute any code and displays error. The following is the function:

function getType(v) {
    if (typeof v === 'undefined')
        return 'undefined';
    else if (v === null) //typeof v will return object if it is null
        return 'null';
    else if (v instanceof Array) //typeof v will return object if it is an array
        return 'array';
    else 
        return typeof v;
}

Example:

getType(thisisundefinedvariable);

Console shows reference error where as according to the code it must return undefined.

EDIT

The browser had gone crazy. Whats the difference between:

getType(thisisundefinedvariable); //This does not work
             AND
getType(window.thisisundefinedvariable); //This works

2 Answers 2

3

The error is not from inside the function, it's from the function call. The attempt to reference the undefined variable in the function call is the error, in other words. You can't force the language to allow you to do that; it's simply erroneous.

Now, this should be OK:

var obj = {};
alert( getType( obj.noSuchProperty ) );
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is not that thisisundefinedvariable is undefined but that it is undeclared.

You can't do anything with undeclared variables (except assign values to then, and then only when you are not in strict mode).

The error occurs when you try to get the variable to pass to the function, not with anything you do with it inside the function.

To declare it, use var.

var thisisundefinedvariable;
getType(thisisundefinedvariable);

Alternatively, pass an undefined object property:

var ob = { foo: 1 };
getType(ob.bar);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.