47

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?

Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123

7 Answers7

96
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;
Amber
  • 507,862
  • 82
  • 626
  • 550
  • Yay for ternary operators. I'll try that out. Edit: Ah, okay. What about 'undefined'? Didn't seem to catch that. – Elliot Bonneville Mar 25 '12 at 22:26
  • What do you mean? The string `'undefined'` is a true value, and is not equal to the actual `undefined` value. – Amber Mar 25 '12 at 22:29
  • 1
    I meant, where the variable hasn't been declared at all. I know the string 'undefined' evaluates to a boolean true, but that's not what I was looking for. – Elliot Bonneville Mar 25 '12 at 22:29
  • When you say it "didn't seem to catch that", what do you mean? If you're dealing with a global variable that may not be defined, you'd probably want to use `window.y` (which will actually return `undefined`) rather than `y` (which could potentially cause an error). – Amber Mar 25 '12 at 22:30
  • I'd initially tried alerting the value of x, but nothing popped up. Further experimentation via console.log showed that y was undefined and it wouldn't even run the `||` statement. – Elliot Bonneville Mar 25 '12 at 22:31
  • See my edited comment above about using `window.y` instead of just `y`. – Amber Mar 25 '12 at 22:31
  • Yep, that does the trick; thanks. Still, I'm curious to know why y's `undefined` didn't evaluate to false and thus lead to x equaling 1. Edit: if I define `window` as `_`, I can then say `var x = _.y || `, which is as short as I could want. I'm only checking to see if y is undefined in this case so I'm not worried about falsy vs. false. – Elliot Bonneville Mar 25 '12 at 22:32
  • -1 — That ternary expression has **exactly** the same result as `x = y || 1`, since null, 0 and '' (empty string) are all `== undefined`. You should use `===` (if that's what the OP wanted). – RobG Mar 25 '12 at 22:47
  • @RobG - Updated to `!==` on matter of princple. That said, `false == undefined` is false. Try it (or just look at http://i.imgur.com/rHXiq.png). – Amber Mar 25 '12 at 23:08
  • its probably better to test for definedness using `typeof` – vol7ron Mar 25 '12 at 23:12
  • @Amber—you have your rep back. – RobG Mar 26 '12 at 00:21
24

Another way to write it shortly

bePlanVar = !!((bePlanVar == false));

// is equivalent to

bePlanVar = (bePlanVar == false) ? true : false;

// and 

if (bePlanVar == false) {
    bePlanVar = true;
} else {
    bePlanVar = false;
}
Hu3nn1
  • 301
  • 2
  • 7
4
y = (y != undefined) ? y : x;

The parenthesis are not necessary, I just add them because I think it's easier to read this way.

haltabush
  • 4,508
  • 2
  • 24
  • 41
3

Other way is using short-circuit:

x = (typeof y !== 'undefined') && y || 1

Although I myself think that ternary is more readable.

Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74
2

Here is a way to do it that works, but may not be best practise for any language really:

var x,y;
x='something';
y=1;
undefined === y || (x = y);

alternatively

undefined !== y && (x = y);
Nemesarial
  • 487
  • 5
  • 12
0

Appears you are having 'y' default to 1: An arrow function would be useful in 2020:

let x = (y = 1) => //insert operation with y here

Let 'x' be a function where 'y' is a parameter which would be assigned a default to '1' if it is some null or undefined value, then return some operation with y.

  • This is not what OP was asking for. You're suggesting that `x` becomes a function unless you immediately invoke that. Even then, this makes the code overly complex, since in JavaScript, default assignments can just be expressed with the `||` operator as @Nemesarial commented in OP or with the ternary operator in accepted answer – vassiliskrikonis Apr 04 '20 at 11:21
0

You can try if/else this shorthand method:

// Syntax
if condition || else condition

// Example
let oldStr = "";
let newStr = oldStr || "Updated Value";
console.log(newStr); // Updated Value

// Example 2
let num1 = 2;
let num2 = num1 || 3;
console.log(num2);  // 2  cause num1 is a truthy
Ericgit
  • 6,089
  • 2
  • 42
  • 53