Search code examples
javascriptarraysboolean-operations

What is the purpose of using OR operation on a varible with empty array?


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']);


Solution

  • 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']);