Issue with 'for' loop iteration over object array

Can someone help me understand why I am getting the unexpected result "6 You have not watched undefined undefined" in the browser console when running this simple code?

var films = [{
    title: "The Mummy",
    hasWatched: true,
    stars: "5 stars"
  },

  {
    title: "About A Boy",
    hasWatched: true,
    stars: "5 stars"
  },


  {
    title: "It",
    hasWatched: false,
    stars: "5 stars"
  },


  {
    title: "Cleopatra",
    hasWatched: false,
    stars: "5 stars"
  }

];

for (var i = 0; i <= films.length; i++) {
  if (films.hasWatched) {
    console.log("You have watched " + films.title + " " + films.stars + ".");
  } else {
    console.log("You have not watched " + films.title + " " + films.stars + ".");
  }

}

Answer №1

If you have an array of objects, make sure to reference the index of each element in the array. Remember to adjust your loop by subtracting one since array indexes start at zero but the length does not.

var movies = [{
    title: "The Mummy",
    hasWatched: true,
    stars: "5 stars"
  },

  {
    title: "About A Boy",
    hasWatched: true,
    stars: "5 stars"
  },


  {
    title: "It",
    hasWatched: false,
    stars: "5 stars"
  },


  {
    title: "Cleopatra",
    hasWatched: false,
    stars: "5 stars"
  }

];

for (var i = 0; i < movies.length; i++) {
  if (movies[i].hasWatched) {
    console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
  } else {
    console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
  }

}

Answer №2

To correct the loop, adjust the for condition to i < movies.length. This change will eliminate the extra iteration. Additionally, make sure to access movies[i] to retrieve the specific movie details, such as movies[i].title.

In the given scenario, the final index is 3 (items are labeled 0, 1, 2, 3), yet your loop extends until 4. Consequently, it will try to fetch movies[4].title and yield an undefined result.

Answer №3

for (let j = 0; j <= films.length; j++) {
  if (films[j].hasSeen) {
    console.log("You've seen " + films[j].title + " " + films[j].rating + ".");
 } else {
    console.log("You haven't seen " + movies[j].title + " " + movies[j].rating + ".");
  }

}

You just forgot to include the correct index when accessing the elements.

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

Error occurred in AngularJS service due to incorrect data type

Looking to store the URL of a query in an AngularJS service like this: var mortgageloanService = angular.module('loanstreetIpadAppApp', []); mortgageloanService.factory('updateTable', function($http) { return { getParams: fun ...

Guide on populating a Vue.js input field with a value retrieved from a JSON object

Could someone please assist me with a problem I am encountering? I need to extract and display the values from an input form for "name" and "position", but the data is in JSON format. {"id":5,"name":"the name","pos":"the position"} This code snippet repr ...

Exploring deeply nested objects within Express by iterating through them

I am trying to figure out how to iterate through objects in Express.js. I can retrieve information from the JSON file, but when I attempt to loop through it, I keep getting an error saying that it's not defined. What could I be missing here? My goal ...

The failure of jQuery AJAX error callback to execute

I'm currently facing an issue with an AJAX call that I have in my code. Here's the code snippet: $.ajax({ type: "get", url: "xxx.xxx.xxx/xxx.js", dataType: 'jsonp', success: function(data) { ...

Instructions for including a sentence in an array as a single element with the split method

I have a string and I want to turn it into an array by splitting it into individual elements. For example: let str = "add 2017-04-25 2 USD Jogurt" str.split(" "); ["add", "2017-04-25", "2", "USD", ...

Is there a more efficient method to tally specific elements in a sparse array?

Review the TypeScript code snippet below: const myArray: Array<string> = new Array(); myArray[5] = 'hello'; myArray[7] = 'world'; const len = myArray.length; let totalLen = 0; myArray.forEach( arr => totalLen++); console.log(& ...

Button from Material-UI vanishes upon being clicked

I encountered an issue with a button that disappears when clicked on. Additionally, clicking the button once does not trigger any actions associated with it. In order to execute the button actions, I have to click the area where the button was located afte ...

Modifying the CSS Property of a Non-React Element within a React Application

I am currently in the process of developing a React-based application that will operate within a Wordpress page. The application is mostly self-contained, but I am interested in being able to toggle the visibility of a div element on the page that is not p ...

ng-repeat not functioning properly with custom tabs

Everything was working perfectly until I added ng-repeat to the content <ul> <li ng-class="{active:tab===1}"> <a href ng-click="tab = tab==1 ? a : 1">Tab1</a> </li> <l ...

Change glb files to draco glb in the frontend

Can we encode and transform glb files into draco glb format using only frontend technologies (client side)? ...

The GIF Loader fails to animate while an AJAX request is in progress

Displaying a DIV element containing a loading GIF image while waiting for an AJAX call response. Initially, the DIV element is hidden. Upon clicking a checkbox, the loader DIV is shown, followed by the completion of the AJAX call, and then hiding the load ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

Laravel: Input information into a form containing multiple dropdown menus

I am in search of a Laravel or HTML example that demonstrates filling out a form with multiple drop-down lists. Here's my scenario: I have the following text inputs: name_customer, phone_customer, email_customer. I want the form fields to automatical ...

I need help converting the "this week" button to a dropdown menu. Can someone assist me in troubleshooting what I am missing?

Seeking assistance with customizing the "this week" button on the free admin dashboard template provided by Bootstrap 4. Looking to turn it into a dropdown feature but unable to achieve success after two days of research and watching tutorials. See code sn ...

Avoiding the hashtag symbol in a serialized string

I have a serialized string that I am sending to the server, structured like this: counter=1&Id=4&type=2332&amount=3232&gstIncluded=3232&paymentMethod=2&notes=2332#fdsf&docId=0&ref=3232&isEdit=true The issue I am encoun ...

Exploring the power of jQuery and Ajax together

Today seems to be one of those days where even the simplest tasks become a challenge. I'm sorry if this question has been asked before, but I'm struggling with a basic issue. I want to dynamically update text on a website using a text file, and w ...

The JavaScript application in Hyperledger Fabric's node app.js isn't functioning properly

As a newcomer to the blockchain industry, I decided to delve into Hyperledger by following the instructions provided in this documentation. After downloading all the necessary prerequisites and setting everything up correctly, I successfully executed the n ...

Certain crucial happenings inhibit the ability of others to occur

Hey there! Want to check out the live application I'm currently working on? Simply click this link: turbo_synth This project is being developed using VueJS, however, the issue I've encountered does not seem to be related to Vue at all. The prob ...

I am in the process of transitioning my JSX website to TSX and am struggling to figure out the proper placement of my type definitions

As the title suggests, I am in the process of migrating an application that I developed using the Google Maps API for rendering maps. In this app, I display information on maps and include functionality to zoom in when a user clicks on something. The erro ...

Show only specific items in an AngularJS application

As a newcomer to AngularJS and the Ionic framework, I'm currently working with the basic Starter Tabs Ionic template. I would like to implement a "Favourite/Bookmark" feature for certain items and display them on a separate tab. The structure of my b ...