1

What does this mean in var definition:

var array = array || [];

... and next two parts of javascript are equal each other?

var array = array || [];
array.push([1],[2]);
array.push([3]);

=

var array = array.push([1],[2],[3]) || [];

?

0

5 Answers 5

2

The first statement will set array to an empty array if it is a falsey value (null, undefined, etc.).

The next two parts are not equal, and will likely fail when you try to call push on something that is not known to be an array.

Sign up to request clarification or add additional context in comments.

Comments

2

It is equivalent to this,

var array;
if(array){
  array = array;
} else {
  array = [];
}

Just in a much shorter form.

In the second part, No those two are not equivalent.

array.push([1],[2],[3])

needs to be executed no matter what, if you use || [] it will not be added.

In other words, you start with this,

var array;
if(array){
  array = array;
} else {
  array = [];
}
array.push([1],[2],[3]);

And you then modified it to this,

var array;
if(array){
  array = array;
  array.push([1],[2],[3]);
} else {
  array = [];
}

1 Comment

Thanks, I'm already resolve this. Im just trying to optimize Google Analytics tracking code.
1

It means that if array is a falsy value (undefined, null etc.) - the value that will be assigned to the var array is an empty array - [];

EDIT:

the second part of your question - no these are not equivalent.

For instance, when array is undefined:

var array = array.push([1],[2],[3]) || [];

this will throw an exception.

This:

var array = array || [];
array.push([1],[2]);
array.push([3]);

will not.

Comments

1

It's setting the var to a new array if it's not defined.

Comments

1

That syntax uses the javascript boolean or operator, and its evaluation of truthy/falsey statements to provide a valid default value.

So

var array = array || [];

Means "use an empty array if array evaluates false".

Comments

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.