Reputation: 347
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
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
example1
Upvotes: 1
Reputation: 780724
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.Upvotes: 2
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