javascriptarraysreturn-valuearray-push

Why does this code return a number instead of an array with the array.push()?


I was asked to write a function that adds an element to the end of an array. However, if the added element has the same value as one of the elements in the array, the element should not be added to the array. Like add([1,2],2) should return [1,2] only

My code is:

  function add (arr, elem){ 

      if (arr.indexOf(elem) != -1){
           return arr;
      }

      else {

           let newArr = arr.push(elem); 
           return newArr; 
      }

  }

  console.log(add([1,2],3)); // here returns a number '3' instead of an array[1,2,3]

Can anyone explain why I got a number instead of the array 'newArr' in else?


Solution

  • Array.push does not return the whole array but the count of the new array

    For example:

    const colors = ['red', 'blue', 'yellow'];
    const count = colors.push('green');
    console.log(count); // expected output: 4
    console.log(colors); // expected output: Array ["red", "blue", "yellow", "green"]