-1

So, I was building a simple rest api on node, I fixed the problem, but I was just curious as to why I even get a number 4 to begin with? You'll know what I mean when you look at the code, It's just a small snippet of code that I'm confused about.

main.js

const people = [
  { id: 1, firstName: "Daniel"},
  { id: 2, firstName: "Erika" },
  { id: 3, firstName: "Christian"},
];

let person = people.push({ id: people.length + 1, firstName: "Mark"})

If I console.log(person) I get 4 as a value. I mean I understand that If I console.log(people) I will get what I added, but I'm just curious as to why when I console.log(person) I get a value of 4?

D932932
  • 1
  • 1
  • 4
    [`Array#push()` returns the new length of the array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) – VLAZ Aug 14 '20 at 13:43
  • `Array#Push` => Returns - *The new length property of the object upon which the method was called.* – Always Helping Aug 14 '20 at 13:45
  • Array.push returns the new length of your `people` array :) – Giovanni Esposito Aug 14 '20 at 13:45
  • [Why does Array.prototype.push return the new length instead of something more useful?](https://stackoverflow.com/q/34259126) | [javascript push returning number instead of object](https://stackoverflow.com/q/43769201) | [Array.push return pushed value?](https://stackoverflow.com/q/23354896) – VLAZ Aug 14 '20 at 13:47

1 Answers1

0

Ciao, as @VLAZ said, Array.push returns the new length of your people array.

If you want to get the last person inserted in people array you could do:

const people = [
  { id: 1, firstName: "Daniel"},
  { id: 2, firstName: "Erika" },
  { id: 3, firstName: "Christian"},
];

let person = people[people.push({ id: people.length + 1, firstName: "Mark"}) - 1];
console.log(person)

-1 because the 4th element of the array is the object in position 3

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30