-5

There is some examples:

a = ''; //string
b = 0; //number 0
b1 = 0xf; //number 15
c = (function(){}) //function function (){}
d = []; //object
e = {}; //object [object Object]
f = void(0); //undefined undefined

but when I try pass undefined variable trougth function like that:

typeof qwerty; //undefined
function at(a){return (typeof a)+' '+a;}
at(qwerty); // ????

..i`v got an error "Uncaught ReferenceError: qwerty is not defined". How can I (Is the shortest way exist to) create function isDefined(a,b) or another trick to reduce that expression?:

c=(typeof a!='undefined'&&a||b)

Clarification: If a is defined - c equals a, overwise - b, like "c=@a?:b" in php

Edit:

function ud(_a){return typeof window[_a]==='undefined'}

a=undefined; b=3;
alert((ud('a')?4:a)+(ud('b')?5:b));​
iegik
  • 1,429
  • 1
  • 18
  • 30

2 Answers2

5
function isDefined(variable, dflt) {
    return typeof variable === "undefined" ? dflt : variable;
}

var c = isDefined(a, b);
Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • Uncaught ReferenceError: a is not defined (Google Chrome 16...) – iegik Jan 12 '12 at 20:04
  • Thats a problem with how your calling the function, you'll need to provide some sample code + all these examples assume that the test variable has been declared, is that not the case? – Alex K. Jan 13 '12 at 08:58
  • http://jsfiddle.net/iegik/grK5X seems to be argument have to declare before pass trougth the function, but it can be undefined. – iegik Jan 13 '12 at 19:38
  • 1
    It fails because in that case `a` is undefined & *undeclared* - the act of passing it to a function fails as js cant resolve the symbol `a` to anything. Move the check to inline rather than a function; http://jsfiddle.net/grK5X/3/ also see http://stackoverflow.com/questions/8531059/how-to-check-if-a-variable-or-object-is-undefined/8531113 – Alex K. Jan 14 '12 at 13:10
1
function def( a, b ) {
    var undef;

    return a === undef ? b : a;
}

And then:

var c = def( a, b );
// if a is defined - c equals a, otherwise b
Esailija
  • 138,174
  • 23
  • 272
  • 326