Exploring the use of the for...in loop and pop() in

Recently I familiarized myself with the arrays for-of loop, and decided to use it to clear out an array by using the pop() method which is supposed to remove the last element of the array. However, this approach doesn't seem to be working as intended.

let skills = ["HTML", "CSS", "Javascript", "SASS", "Bootstrap", "Tailwind"];
for (let skill of skills) {
  skills.pop();
}
console.log(skills); // HTML , CSS, Javascript

Answer №1

An array iterator functions like a dynamic collection; as the array is modified during iteration, the items returned by the iterator will reflect these changes. By incrementing an index from 0 to the array's length, the iterator navigates through the elements seamlessly.

for (let skill of skills) {

In this context, the previous code snippet is almost identical to

for (let i = 0; i < skills.length; i++) {
  const skill = skills[i]

The array iterator does not return a fixed set of items upon initialization; rather, each item returned is determined dynamically during iteration. Therefore, if you remove an item using .pop within the loop, there will be fewer iterations compared to when no removal occurs, except when already at the end of the array.

For instance, with 6 items in the array - as present here - and popping 3 times would result in only 3 iterations remaining out of the original 6, along with 3 items removed.

If the array remained unchanged while being iterated, the .pop method would function normally. However, it's worth noting that there are more efficient ways to clear an array than this approach.

let skills = ["HTML", "CSS", "Javascript", "SASS", "Bootstrap", "Tailwind"];
for (let skill of [...skills]) {
  skills.pop();
}
console.log(skills); // empty

The trick lies in using [...skills] to create a separate array where elements remain intact even after calling skills.pop.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The combination of curly brackets and displaying items in a list

What is the reason behind React's failure to render the list items when the arrow function objectList contains curly braces? export default function StatelessList() { const objDev = [ { id: 1, surename: "John", name: "Wayne" ...

How to Use an Array to Filter Another Array in AngularJS

After attempting to filter a group of checkboxes using an array, the outcome was not what I expected: <ion-checkbox ng-repeat="user in users | filter: {id: group.members}" ng-model="user.checked">{{user.info.name}}</ion-checkbox> The specific ...

Adding an element to a nested array within a targeted element of a main array (MongoDB)

I am reconsidering the data structure currently stored in the Users Collection. Previously, my server would receive messages, locate the user document with the correct profile.website field, and add an item to the profile.siteMessages array: { "_id": "h ...

Implementing a dynamic display of images using JavaScript: a step-by-step guide

I have a set of 4 light bulbs: <div id="bulb1" class="lightbulb"><img src=".\images\bulb.png" /></div> <div id="bulb2" class="lightbulb"><img src=".\images\bulb.png" /></div> <div id="bulb3" class ...

A guide on transferring data to an external JavaScript script that is asynchronously loaded

I came across this solution on Stack Overflow here to load JavaScript asynchronously. However, I am wondering how can I pass some data to the external file? This is my current code: <script id="js-widget-o2ba1y" type='text/javascript'> ...

Issue with enabling Picture-in-Picture feature on iOS Progressive Web Apps

My goal is to enable Picture-in-Picture (PiP) on an HTML video by using the code below: await videoElement.requestPictureInPicture().catch((error) => alert(`PiP failed, ${error}`); ); While this code works perfectly in Safari, I encountered an iss ...

Execution of Javascript code does not provide the expected output when run via VS Code

I've attempted numerous times, but the desired output doesn't appear when I run it through VS Code. However, this code runs smoothly and produces the desired output when executed in Replit's online code editor. Can anyone offer assistance? l ...

Obtain a URL using JavaScript's regular expressions

Is it possible to use JavaScript regex to fetch the first function parameter? For instance, when I click on a tag in this page element, how can I extract the inline link? Here's an example: <li><a href="#blog" data-rel="clos ...

Adding additional text will not render d3.js' output

I'm struggling with a simple issue here, My goal is to add a div to my svg element containing text. I have written the code for this and in the DOM, it shows that the svg has the correct class attached along with the desired text. However, the text i ...

Is there a way to retrieve just 6 documents with a "true" value in a specific field?

I am working with a controller that uses the following code snippet: Model.find().sort('date').limit(6).exec(function(error, result) { if (error) { console.log(error); } else { res.send(result); } }); In my databas ...

Retrieving the data from an AJAX JSON variable

Inside my JavaScript function, I am fetching data like this: var jsonData = $.ajax({ url: "pie_chart_community.php", community_id: $c_id, dataType: "json", async: false }).responseText; Is there a way for me to access the community_id in ...

Validating JSON arrays using schema objects

My task involves validating a JSON message with the following structure: { "header": { "action": "change_time", "taskGuid": "someTaskGuid", "publishDate": "2012-04-23T18:25:43.5 ...

In the world of mathematics, the equation 1+1 may actually equal 11 instead

I have a TypeScript class where there are no import statements at the top. The issue I am facing is that when I use calculateDate() and run the addMonth(new Date(), 1) function, it ends up adding 11 months to today instead of just 2. Upon investigation, ...

Do we really require the hitCallback feature in Google Analytics for tracking onsite activities?

Currently, I am in the process of integrating Google Analytics into a website. Within this website, there is a page A that contains two links to page B on the same domain. My goal is to use GA to track which navigation path the user took to go from page A ...

Clicking on the menu to reveal the dropdown options using JavaScript

I have created a drop-down menu for my website, but I am facing an issue. When I click on the links again, it does not work properly because I lack expertise in JavaScript. I would appreciate any help and suggestions from all of you. Thank you for your tim ...

Unable to iterate through Ajax calls using For Loop when onChange event occurs

I'm struggling with looping the OnChange method using an AJAX call, but for some reason, it's not working as expected. for (let index = 0; index < 300; index++) { $('#txtLini'+[index]).on('change', function() { ...

What is the best way to display the items from a list that meet specific criteria?

When displaying data, I am looking to only show specific objects that contain certain values. Take for example this set of data: { "product": [ { "name": "laptop", "markets": [ "Portu ...

How to Resolve jQuery Script Delay Caused by AJAX Request?

I am in the process of creating a unique responsive Wordpress Theme, with only one page that loads content via AJAX. Here is the AJAX function I have implemented: jQuery(document).ready(function(){ jQuery.ajaxSetup({cache:false}); jQuery(" ...

Scroll automatically to the following div after a brief break

On my website, the title of each page fills the entire screen before the content appears when you scroll down. I am interested in adding a smooth automatic scroll feature that will transition to the next section after about half a second on the initial "ti ...

Swap out a web link for an embedded iframe

Currently working on updating internal links: <div class="activityinstance"> <a href="http://website.com/hvp/view.php?id=515512">activity</a> </div> The goal is to convert them into: <div class="activityinstance"> ...