javascript: define a variable if it doesn't exist

Viewed 97366

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;)

15 Answers
if (typeof variable === 'undefined') {
    // variable is undefined
    // eg:
    // var variable = "someValue";
}

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.

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;

I prefer a general solution in PHP-like style:

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

Cleanest way in 2022 ECMA syntax!!

If you want to overwrite "nullish" values (see ref below), assign using let might_exist ||= default or pass value with (might_exist || default). (The parentheses are only there for clarity and to avoid operator precedence problems, delete if you'd rather.)

If you want to keep "nullish" values, assign using let might_exist ??= default or pass value with (might_exist ?? default).

On being nullish: ?? will only overwrite null and undefined, whereas || will also overwrite "nullish" values like '' and 0.

You're all very welcome, it's about time I gave back a lil

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment

if(embed_BackgroundColor == "" || embed_BackgroundColor == 'undefined' || embed_BackgroundColor == null){
}
Related