views:

1160

answers:

4

hey everybody, i feel like im trying to do something super simple, but just being stupid about it.

all i want to do is see if a variable has been set previously, and if it has NOT, set it with a default value....here is a sample:

if(!embed_BackgroundColor) {
    var embed_BackgroundColor;
    embed_BackgroundColor = "#F4F4F4";
}

so, once you stop laughing at my code....WHY is it overwriting the variable no matter what?

please save my nerves;)

+6  A: 
if (typeof variable === 'undefined') {
    // variable is undefined
    // eg:
    // var variable = "someValue";
}
Paolo Bergantino
the problem is that no matter what the // var variable = "someValue" is overwriting the pre-defined value that DID exist
johnnietheblack
is that really three =s? (i don't know)
jedierikb
A: 

I think your posted code should work. Unless your original value is 0.

The problem is somewhere else.

I'm guessing you defined 'embed_BackgroundColor' out of the scope of your code. And when you run your code, that variable is undefined with in the scope of your code, and will be assigned the default value.

Here is an example:

var embed_BackgroundColor = "#FF0000";

(function(){
  if(!embed_BackgroundColor) {
    var embed_BackgroundColor;
    embed_BackgroundColor = "#F4F4F4";
  }
  alert(embed_BackgroundColor); // will give you #F4F4F4
})();

alert(embed_BackgroundColor); // will give you #FF0000;
Aaron Qian
A: 

I prefer a general solution in PHP-like style:

function isset(x) { return typeof(x)!='undefined'; }

Thinker
this won't work. It'll give you a reference error: [x] is not defined.
KooiInc
It works, but you need to remember, that isset(obj.arr[x]) won't work if you don't check first for isset(obj) and then isset(obj.arr).
Thinker
+3  A: 

It would be a good coding practice in this case to use the ternary operator. Also you don't need to have three equal signs when comparing with typeof. This is the most concise solution:

b = typeof(b) == 'undefined' ? 0 : b;

This hopefully will save your hands some time.