Shorthand if/else statement Javascript
var x = y !== undefined ? y : 1;
Note that var x = y || 1;
would assign 1
for any case where y
is falsy (e.g. false
, 0
, ""
), 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 window.y
.
As vol7ron suggests in the comments, you can also use typeof
to avoid the need to refer to global vars as window.<name>
:
var x = typeof y != "undefined" ? y : 1;
Another way to write it shortly
bePlanVar = !!((bePlanVar == false));// is equivalent tobePlanVar = (bePlanVar == false) ? true : false;// and if (bePlanVar == false) { bePlanVar = true;} else { bePlanVar = false;}
y = (y != undefined) ? y : x;
The parenthesis are not necessary, I just add them because I think it's easier to read this way.