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);
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.
pop() mutate the array by adding (pushing) or removing (popping) the last item (poop).
pop() The pop() method removes the last element from an array and returns that element. This method changes the length of the 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.
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
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With