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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Note that
var x = y || 1;would assign1for any case whereyis falsy (e.g.false,0,""), which may be why it “didn’t work” for you. Also, ifyis a global variable, if it’s truly not defined you may run into an error unless you access it aswindow.y.As vol7ron suggests in the comments, you can also use
typeofto avoid the need to refer to global vars aswindow.<name>: