28

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!!!

2
  • 1
    the return value is the new length, this is expected. the original array is mutated so you don't need to return it Commented May 3, 2017 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) Commented May 3, 2017 at 21:39

1 Answer 1

39

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Even with above solution, it returns the length of the array and not the final array
@vikramvi then after pushing new element, return whole array - return reminders;
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; }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.