Minh Cường
Minh Cường

Reputation: 347

Javascript: || operator for variable assignment

I have two small examples code:

// example 1:
var x;
...
x = x || 'some value'; //assign some value to x if x has no value
...

// example 2:
var y;
...
y || (y = 'some value'); //assign some value to y if y has no value
...

My question is:
1. Will x be reassign it's value in example 1 when x already has value?
2. Is example 2 better then example 1?

(My english isn't good. Thanks for your reading and answering :D)

Upvotes: 4

Views: 1481

Answers (3)

Dyrandz Famador
Dyrandz Famador

Reputation: 4525

x will just reassign it's value since it has already a value

    var x = 'foo';
    x = x || 'some value';
  //  result: x = 'foo' //reassigned the value of x
  • In terms of readability, i would prefer the example1

Upvotes: 1

Barmar
Barmar

Reputation: 780724

  1. Yes. If x has a truthy value, it will be assigned back to itself. If it doesn't, the default 'some value' will be assigned to it.
  2. There may be a tiny performance benefit in example 2, but example 1 is the standard idiom. Consistency with other programmers is useful because they'll understand your code more easily. Unless you're doing lots of default value initialization in a large loop, the performance gain should be negligible.

Upvotes: 2

grodzi
grodzi

Reputation: 5703

in example 1, javascript assigns at first pass value undefined to x. at second pass (when your code is running) x comes with value undefined at line

var x;

then || operator acts as following. Consider having :

left || right

if(left is not undefined (globally resolved to true) then return left else return right

so yes a value will be reassigned to x (either x itself or 1) As x resolved to undefined, or operator resolves right, and then assigns 1 to x. so x = x||1, ends in x's value === 1

second example no it adds uncomplicated logic (but still works)

Upvotes: -1

Related Questions