Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pop() is not a function - nodejs

I am having a strange error with NodeJS when I call the function pop() on an array, it says TypeError: cars.pop is not a function... I am confused.

Any help? Below is the code. Thank you,

//callback chaining to avoid having multiple callbacks in the event queue
//only one callback calling others
function showCar(car, callback) {
  console.log('Saw a ' + car);
  if (car.length) {
    //register the function as asynchronous
    process.nextTick(function() {
      callback();
    })
  }
}

function logCars(cars) {
  var car = cars.pop();
  showCar(car, function() { //chaining of call backs
    logCars(car);
  });
}
var cars = ['ferrari', 'porsh', 'Hyundai', 'Peugeot'];
logCars(cars);
like image 921
Celaro Avatar asked Jan 30 '17 00:01

Celaro


People also ask

How do I pop an array In Node JS?

pop() is an array function from Node. js that is used to remove elements from the end of an array. Parameter: This function does not takes any parameter. Return type: The function returns the array.

Does pop mutate the array?

pop() mutate the array by adding (pushing) or removing (popping) the last item (poop).

What is pop () in JS?

pop() The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

How do you remove the last element of an array?

JavaScript Array pop() The pop() method removes (pops) the last element of an array. The pop() method changes the original array. The pop() method returns the removed element.


1 Answers

It's because you aren't passing an array to the logCars function on the second call. You are passing the popped string on the second recursive call.

In other words, logCars(car) should be logCars(cars) where you are nesting callbacks:

function logCars (cars){
  var car = cars.pop();
  showCar(car, function () {
    logCars(cars); // This should be `cars`, not `car` like you had
  });
}
like image 178
Josh Crozier Avatar answered Oct 24 '22 04:10

Josh Crozier