title: Can I limit the length of an array in JavaScript?
body: <p>I want to display the product browsing history, so I am storing the product ids in a browser cookie.</p>
  
  <p>Because the list of history is limited to 5 items, I convert the cookie value to an array, then check the length of it and cut the redundant. </p>
  
  <p>The code below is what I have tried, but it does not work; the array item isn't removed.</p>
  
  <p>I would like to ask how to limit the array length so it can only store 5 items?</p>
  
  <p>Or</p>
  
  <p>How can I cut the items after the array index 4?</p>
  
  <pre><code>var id = product_id;
  var browseHistory = $.cookie('history');
  if (browseHistory != null) {
    var old_cookie = $.cookie('history');
    var new_cookie = '';
  
    if (old_cookie.indexOf(',') != -1) {
      var arr = old_cookie.split(',');
      if (arr.length &gt;= 5) {
        arr.splice(4, 1)
      }
    }
  
    new_cookie = id + ',' + old_cookie;
    $.cookie('history', new_cookie, { expires: 7, path: '/' });
  } else {
    $.cookie('history', id, { expires: 7, path: '/' });
  }
  </code></pre>