I’m wondering if there’s a shorter way to write this:
var x = 1; if(y != undefined) x = y;
I initially tried
x = y || 1, but that didn’t work. What’s the correct way to go about this?
var x = y !== undefined ? y : 1;
var x = y || 1; would assign
1 for any case where
y is falsy (e.g.
""), which may be why it “didn’t work” for you. Also, if
y is a global variable, if it’s truly not defined you may run into an error unless you access it as
As vol7ron suggests in the comments, you can also use
typeof to avoid the need to refer to global vars as
var x = typeof y != "undefined" ? y : 1;