Set a variable only if it is undefined (Javascript)

When relying on variables within a global scope, it's often wise to set a sane default within your script. However, it's important to ensure that that only occurs if the variable isn't already set (so that values set within the page itself are not overwritten, and nor are values propogated to that value if the script is called a second time for some reason).

Details

  • Language: Javascript

Snippet

var foo = (foo === undefined) ? 'bar' : foo;

Usage Example

var foo = (foo === undefined) ? 'bar' : foo;
console.log(foo);
# bar

var bar = 'sed';
var bar = (bar === undefined) ? 'won' : bar;
console.log(bar);
# sed