Set a variable only if it is undefined



Published: 2019-03-27 17:56:36 +0000
Categories: Javascript,

Language

Javascript

Description

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

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

Keywords

JS, undefined, default, value, variable,

Latest Posts


Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter