0

I have a function:

function goError(thing){

    console.log(typeof(thing)); //RETURNS A STRING 'UNDEFINED'

    if(typeof(thing) != undefined){
        console.log(thing); //RETURNS UNDEFINED
        return thing;
    }

    throw 'Error: ' + thing;
}

I'm trying to get down to the error message. But when I pass through a parameter of undefined, the function works correctly, which is not what I want.

When I console out the undefined variable, I get undefined, but when I console out typeof(thing) I get a string 'undefined'. This string obviously isnt causing my error to kick in.

I could alter the function as follows, it works fine then and I can get to my error.

    if(thing != undefined){
        return thing;
    }

But can I cause the error to kick in without altering the func?

What can I pass into my function that will cause the error?

Daft
  • 10,277
  • 15
  • 63
  • 105
  • 2
    correct, `typoeof` returns the type as a string, so you should write `typeof thing !== 'undefined'` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – Joram Nov 28 '14 at 13:44
  • So the function is incorrect as it currently is written? – Daft Nov 28 '14 at 13:45

3 Answers3

2

To check if thing is undefined, you must do:

if(typeof thing !== "undefined") {
    // well, it seems to have something
}

And a fiddle, if needed.

lante
  • 7,192
  • 4
  • 37
  • 57
1

Try with this code

function goError(thing){    

    if(thing){        
        return thing;
    }
    throw 'Error: ' + thing;
}
prog1011
  • 3,425
  • 3
  • 30
  • 57
1

Seeing that you're using Angular, you can use the angular.isDefined utility method, docs:

function goError(thing){

    if(angular.isDefined(thing)){
        return thing;
    }

    throw 'Error: ' + thing;
}
Jon Snow
  • 3,682
  • 4
  • 30
  • 51