javascript - function doesn't respect closure


Keywords:javascript 


Question: 

I'm trying to execute a function for each item in array, i'm aware of the closure and compensating for this by using the ES6 let and tried using forEach as following:

       this.tourIDS = [];
         this.tours.forEach(tour => {
         this.tourIDS.push(tour.tour_id);
       });

       this.tourIDS.forEach(id => {
         this.map.setFilter('routes', ['==', 'tour_id', id]);
           console.log(id);
       });

this is mapboxgl setFilter function that takes a query parameter like this ['==', 'tour_id', id], the idea here is to pass the id from the tourIDS array once for each id it contains. so the expected behavior is to have the function executed on every element in the array but only the last element in the array is what gets executed same as if there was no closure however the console.log(id) gets executed right logging each element, so why would console.log works and another function don't ?!


1 Answer: 

as @Keith emphasized in his comment, this is not something wrong with the loop but with the nature of the mapbox-gl js setFilter itself as recalling the function overwrites the previous filter.