27

I'm sure this is just some simple silly mistake that I'm missing, but can anyone tell me why 3 is being returned instead of [{ "method": 'popup', "minutes": ''}, {"method": 'email', "minutes": '10'}, {"method": 'popup', "minutes": '20'}];?

I made a jsfiddle so you can see as well: https://jsfiddle.net/qk10arb0/3/

HTML

<p>Click the button to add a new element to the array.</p>

<button onclick="addNewReminder()">Try it</button>

<p id="demo"></p>

Javascript

function addNewReminder(){
      var newReminder = {
        "method": 'popup',
        "minutes": '20'
      };

      var reminders = [{
                "method": 'popup',
                "minutes": ''
              }, {
                  "method": 'email',
                  "minutes": '10'
              }];

    reminders = reminders.push(newReminder);
    document.getElementById("demo").innerHTML = reminders;
}

Thanks!!!

Rbar
  • 3,740
  • 9
  • 39
  • 69
  • 1
    the return value is the new length, this is expected. the original array is mutated so you don't need to return it – aw04 May 03 '17 at 20:17
  • I do think @kind user's response is clearer as to fix it and the title and approach of this question may make it easier for others experiencing the same issue to find and understand, but I can certainly mark this as a duplicate if you think so. Similar topic, but different explanation in my eyes (hopefully helpful to others that make the silly mistake going forward too) – Rbar May 03 '17 at 21:39

1 Answers1

38

Array#push method works in situ, you don't have to assign it to a new variable. It won't return a new array, but will modify the original one and will return it's length. That's why you are getting 3 as the result.

To get the desired result, just call it, without assigning to any variable:

reminders.push(newReminder);
kind user
  • 40,029
  • 7
  • 67
  • 77
  • 2
    Even with above solution, it returns the length of the array and not the final array – vikramvi Jun 28 '19 at 09:43
  • 3
    @vikramvi then after pushing new element, return whole array - `return reminders;` – kind user Jul 09 '19 at 16:56
  • ```function addNewReminder(){ var newReminder = { "method": 'popup', "minutes": '20' }; var reminders = [{ "method": 'popup', "minutes": '' }, { "method": 'email', "minutes": '10' }]; reminders.push(newReminder); document.getElementById("demo").innerHTML = reminders; }``` – ÄR Âmmãř Żąîñh Feb 25 '23 at 14:56