4

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)

1
  • 2
    1) Depends on the value. 2) Better in which sense? Commented Mar 5, 2015 at 7:22

3 Answers 3

2
  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.
Sign up to request clarification or add additional context in comments.

2 Comments

thanks @Barmar, your answer is very clear and complete
My guess would be that if (!y) y = 'some value'; is just as common (and definitely better / more widespread than example 2).
1

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

2 Comments

The assignment x = x will still take place, so yes, x gets assigned the value it already has.
I got it now @Felix, kinda little bit confused a while ago.. :)
-1

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)

2 Comments

|| does not have a lot to do with undefined. And how does it matter that undefined is a global identifier?
|| does have to do with undefined as undefined resolves to false for a boolean conversion. And || does check the boolean value of its operand. So in ( undefined || soomethingelse), the expression soomethingelse will be executed And I didn't mean undefined to be a global identifier. Globally refers to the left operand to be true (e.g false, null, 0..) so the right operand is not executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.