Home > Net >  How to pop an array on a different function?
How to pop an array on a different function?

Time:11-23

In my little experimental code here about push and pop methods, I wanted to use the pop method on a different function in order to call it whenever i wanted to remove the last element.

So i got confused, and every time i try to pass my pop function it won't work can anyone give me tips or enlighten me how to do this because i can't seem to find any solutions on the net.

const studentInfo = [];

function insertstudentInfo() {
    const student1 = {
        name: "Mark Wizkhalifa",
        grade: 95
    };
    const student2 = {
        name: "Henry Cavil",
        grade: 89
    };
    const student3 = {
        name: "James Gordon",
        grade: 90
    };

    studentInfo.push(student1, student2, student3);

    return studentInfo;
}

console.log(insertstudentInfo());

function popstudentInfo(insertstudentinfo) {
    studentInfo.pop(student1);

    return studentInfo;
}

console.log(popstudentInfo());

CodePudding user response:

When you are calling this function

function popstudentInfo(insertstudentinfo) {
  studentInfo.pop(student1);

  return studentInfo;
}

variable student1 is not defined and this is why an error is thrown. Second thing is that Array.prototype.pop takes no arguments, so you can't pass anything into the .pop() function call

Another thing is that the argument you defined in the popstudentInfo function is not used anywhere, you can delete it.

const studentInfo = [];

    function insertstudentInfo() {
      const student1 = { name: "Mark Wizkhalifa", grade: 95 };
      const student2 = { name: "Henry Cavil", grade: 89 };
      const student3 = { name: "James Gordon", grade: 90 };

      studentInfo.push(student1, student2, student3);

      return studentInfo;
    }

    console.log(insertstudentInfo());

    function popstudentInfo() {
      studentInfo.pop();

      return studentInfo;
    }

    console.log(popstudentInfo());

This code should work, just keep in mind that when you console.log stuff like that (pop and push mutate the original object) your logs can reflect the newest version of the object and it might be misleading. This is why it's recommended to not mutate stuff but I guess this is a lesson for later, no worries now. Just don't be surprised when you look at the console and see two identical logs when these should be different.

  • Related