looping through the elements in a collection using a for-in loop

Issue with IE 11 Console

Chrome Console Behavior

When changing the word 'item' to 'anotherItem' in the loop like so:

var obj = {
    id1: 'item 1',
    id2: 'item 2',
    id3: 'item 3'    
};
for (anotherItem in obj){
    console.log(anotherItem);
}

The loop runs smoothly

Questioning why IE 11 struggles with the keyword 'item'

Answer №1

item is defined as a built-in function in Internet Explorer, potentially read-only, which explains why you are unable to change its value.

Prior to the Edge browser, Microsoft was not consistent with following standards and included various features that deviated from standard practices. The item function is notably absent in Edge.

In addition, make sure you declare anotherItem before using it. Here's an example:

Try the following code snippet:

var obj = {
    id1: 'item 1',
    id2: 'item 2',
    id3: 'item 3'    
};

for (var anotherItem in obj){
    console.log(anotherItem);
}

If you fail to use the var keyword when declaring a variable and you're not operating in strict mode, it will be treated as a global variable unintentionally. Global variables act as properties on the global object, typically the window object in a web browser environment.

To prevent such errors, add the following line at the beginning of your JavaScript file to enforce strict mode:

"use strict";

You also have the option to apply strict mode only to specific functions like this:

(function() {
    "use strict";
    // code within this function is subject to strict mode
})()

Answer №2

Feel free to utilize this code snippet for outdated web browsers. Best of luck!

var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

function myFunction(item, index) {
   document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}

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

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...

What could be causing the JQuery Post and Get methods to not respond or execute when they are invoked?

I'm currently working on a project where I need a webpage to automatically open other pages using the post method through a script, without requiring direct user input. I've tried using the JQuery post method, but haven't had any success so ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: Here is what I have been able to achieve: In the second picture, the divs are shown separately. My goal is to display the incoming data in a single popup like in the first picture, but I am having trouble a ...

How do I define the specific icon to display on the splash screen for progressive web apps?

In my Progressive Web App (PWA), I have set icons at sizes 144 and 512. Although both icons appear in the application tab in Chrome, the splash screen displays a really small icon (I assume it's using the 144 icon). Is there a method to indicate which ...

The JavaScript array slideshow is experiencing some glitches in its transition

After diving into JavaScript recently, I managed to center a div and make it fullscreen as the window resizes. However, things got tricky when I added a script I found online to create an image transition using an array. Unfortunately, these scripts are co ...

Simulated alternate identities for UI Router

I am managing a group of pages/URLs that share a common parent state/template: /orders/list /orders/create /products/list /products/create Currently, I have two dummy states/routes (/products and /orders) that serve as parent states for the other substat ...

Leveraging python capabilities within html documents

English is not my first language, so please excuse any spelling errors. I am working on combining HTML and Python to develop a graphical user interface (GUI) that can communicate with a bus system (specifically KNX bus). Currently, I have a Raspberry Pi ...

Ways to stop touch events on every element but one through JavaScript

One issue I encountered was preventing scrolling in the background while a popover is open. For desktop, it's simple with CSS: body { overflow: hidden; } The problem arose on IOS where this rule didn't work as expected and the background could ...

When a named capture group is included in the regex of a GET path, Express crashes with the error message: "Cannot read property 'name' of undefined at Layer

I am looking to process a GET request and extract specific information from the URL. Let's consider this scenario: const REGEX_QUERY = /^\/?house\/(?<street>[a-z]+)\/(?<house>[0-9]+)$/i; const REGEX_QUERY_NO_NAMES = /^\ ...

"Critical issue: Meta tags are not present on the dynamic pages of the NextJS

In my NextJS application, the pages are structured as follows: App --pages ----_app.js ----index.js ----company.js ----users ------[userID].js I have a dynamic page named [userID].js that retrieves the userID through the router to display information for ...

Only display PHP page content if accessed through an AJAX request, not through directly typing the URL into the address bar

Is there a way to verify if a PHP page has been accessed via an Ajax request? I'm working on a page that displays a form for updating some database data (update.php), but I only want it to be accessible if it is called by a specific page named "change ...

"Converting a basic function into a promise for an AngularJS tutorial: How to handle the error message '

To help my colleagues understand AngularJS, I am creating a dummy exercise. In this example, I want to call a service that provides an Object Array to be passed into a Controller and assigned to a $scope variable (using information about the Beatles). Inst ...

Having trouble receiving the response from PHP after making an AJAX request

Can you help me figure out why I'm not receiving any return value from the ajax data post? Take a look at my code and let me know where I might be going wrong. Here is a snippet of my jQuery code: $("#btnlogin").click(function(){ var email = $( ...

MenuIcon Component is experiencing difficulty being rendered

I am attempting to construct an IconMenu within the AppBar Component. My project is being developed using create-react-app. This is how my code appears: index.js import React from 'react'; import ReactDOM from 'react-dom'; import &a ...

Breaking down a large array in Node.js to initiate multiple API calls

I am currently faced with a challenge where I have a CSV file containing 21k records, with each record being a single alphanumeric word. I need to process these records by sending them to an API in JSON key-value pair format. The API can only accept 500 el ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...

"Adding an Image to Another Image in HTML or JavaScript: A Step-by-Step

Hello there! I'm currently working on creating a status bar where I can add an image after another image. Let me explain my idea clearly. So, I have two images in GIF format: one is white and 10x10px, and the other one is black and also 10x10px. On ...

Tips for expanding frisby.js by adding new "expect" functionalities?

Looking to enhance the Frisby.js module with custom expect methods without altering the source code. These extensions are tailored for my REST API to streamline common tests into a single method. An issue arises as the Frisby.js module exports its methods ...

JavaScript's Ajax request seems to be stagnant and inactive

Having some difficulties with the code below. It triggers an alert correctly, but the ajax part doesn't seem to be functioning. No errors or indications of what's wrong. $(document).on('change', '.department_select', function ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...