1

Is this a legitimate way to update variables and keep the original value if the new value is undefined?

variable = NEWVAR || variable;

I created a Fiddle and so far it looks fine, but I don't want to get any nasty surprises.

Here is a test case:

var test = "hello";

test = undefined || test;

alert('"' + test + '"');
Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
Stefan
  • 14,826
  • 17
  • 80
  • 143

2 Answers2

1

Yes and no. It technically works, but you have to be careful of falsy values because if NEWVAR is 0, false, "", or any other falsy value, it won't be assigned. A wiser way to do this would be to check whether or not NEWVAR is defined, perhaps with a tertiary operator:

variable = (typeof NEWVAR === "undefined") ? variable : NEWVAR;
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • 1
    wouldn't typeof return something like "Object", "Array" etc... I think you meant `typeof NEWVAR !== 'undefined'` – eis Mar 12 '13 at 13:43
  • @eis: Whoops, missed that. Thanks. – Elliot Bonneville Mar 12 '13 at 13:43
  • You can see it the other way round either, this can come in pretty handy if you don't want **any falsy** value e.g `""` to be assigned. It's more about keeping in mind what evaluates `falsy` Oh and @ElliotBonneville isnt this a `ternary` operator ? =) – Moritz Roessler Mar 12 '13 at 13:45
  • @eis: Thanks for the edit, but you've got it backwards. See [this fiddle](http://jsfiddle.net/KYhYY/). :) – Elliot Bonneville Mar 12 '13 at 13:47
  • @ElliotBonneville yeah, misread the intent of OP. Used to backwards way of using. – eis Mar 12 '13 at 14:04
1

I would say, yes, i use it quite often. But you have to keep in mind that

Douglas Crockford: Javascript The Good Parts (p. 40)

The || operator produces the value of its first operand if the first operand is truthy. Otherwise, it produces the value of the second operand.

So if NEWVAR contains any falsy (false,null,undefined,NaN,0,"") value, the second opertand is evaluated.

As long as you are aware of this you can always use the || operator to get default values

Douglas Crockford: Javascript The Good Parts (p. 51)

The || operator can be used to fill in default values:

var middle = stooge["middle-name"] || "(none)";
var status = flight.status || "unknown";
Moritz Roessler
  • 8,542
  • 26
  • 51
  • Thanks, falsy values are ok for me, since I want to keep the original value in that case too – Stefan Mar 12 '13 at 16:19