1

I found that implementation on a google analytics script in one of my project pages.

I was wondering what is the purpose of first line : "myArray || [] "" ?

Why to use OR operation on an array with another empty array?

  var myArray = myArray || [];
  myArray.push(['_setAccount', 'UA-39103830-1']);
  myArray.push(['_trackPageview']);
Nick W
  • 65
  • 1
  • 2
  • 11
  • Or on any other kind of object,does not have to be array. Why to OR it with another empty array? – Nick W Sep 20 '16 at 08:51

2 Answers2

0

This "or" operation assigns an empty array to myArray if it does not exist. The code above is functionally equivalent to:

if(myArray == null || myArray==undefined)
    myArray = [];
myArray.push(['_setAccount', 'UA-39103830-1']);
myArray.push(['_trackPageview']);
AhmadWabbi
  • 2,253
  • 1
  • 20
  • 35
-1

If you observe the below snippet, it checks for falsy values such as undefined null, 0, -0, 0n, "" and NaN (but also empty arrays []) it will assign the right if so.

var arr; // undefined
var arr = arr || [];
console.log(arr) // Output: []

var arr = null; // null
var arr = arr || [];
console.log(arr) // Output: []

var arr = ""; // empty string
var arr = arr || [];
console.log(arr) // Output: []

var arr = "Mr.7"; // string
var arr = arr || [];
console.log(arr) // Output: Mr.7
n1ru4l
  • 488
  • 1
  • 10
  • 29