Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: define a variable if it doesn't exist

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

like image 989
johnnietheblack Avatar asked Apr 02 '09 20:04

johnnietheblack


People also ask

Can you declare a variable without value in JavaScript?

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. A variable declared without a value will have the value undefined .

Does not exist condition in JavaScript?

Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.

What if a variable is not declared in JavaScript?

This JavaScript exception variable is not defined occurs if there is a non-existent variable that is referenced somewhere. Cause of Error: There is a non-existent variable that is referenced somewhere in the script. That variable has to be declared, or make sure the variable is available in the current script or scope.


1 Answers

Pro style:

var SomeVar = SomeVar || 'Default Value'; 
like image 76
Pikachu Avatar answered Oct 19 '22 11:10

Pikachu