What causes this loop to operate in one location but not in another?

import { log, logTitle } from "logger";

var persons = [
  {name: "Alex", age:22},
  {name: "Maria", age:30}
]

var number = 0;

for (var i = 0; i <= persons.length; i++) {
  log(persons[i].name);
  log(persons[i].age);
  log("----------------");
  log(number)
};

while(number < 5) {
  log(number);
  number += 1;
}; 

The for loop will display output on the screen, however, in this case, the log statements within the while loop are not displayed. By rearranging the loops and putting the while loop first, both sets of logs run successfully as shown below:

while(number < 5) {
  log(number);
  number += 1;
};
for (var i = 0; i <= persons.length; i++) {
  log(persons[i].name);
  log(persons[i].age);
  log("----------------");
  log(number)
};


In addition, if the for loop is commented out, the log statements within the while loop become visible.

Lastly, provided below is the code snippet from the imported logger file:

import $ from 'jquery';
export const log = content => $('#content').append("<i style = 'color: black' class = 'fa fa-terminal'> </i>  " + content + "<br>" );
export const logTitle = title => $('#title').append(title);

Answer №1

In this scenario, the variable persons.length has a value of 2, but there are only two indices in the persons array. Therefore, the correct loop expression should be

for (var i = 0; i < persons.length; i++)
instead of
for (var i = 0; i <= persons.length; i++)

var persons = [
  {name: "Alex", age:22},
  {name: "Maria", age:30}
]

var number = 0;

for (var i = 0; i < persons.length; i++) {
  console.log(persons[i].name);
  console.log(persons[i].age);
  console.log("----------------");
  console.log(number)
};

while(number < 5) {
  console.log(number);
  number += 1;
};

Answer №2

The reason for the issue is a mistake in the loop condition of the initial loop. If you modify i <= persons.length to i < persons.length, it should resolve the problem and work as intended.

An error is triggered during the evaluation of persons[2].name within the loop.

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

Load and execute a dynamically created script in JavaScript at the same time

I am exploring the option to load and evaluate a script from a third-party synchronously. Here is an example that currently works well: <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Error encountered when trying to access the _id property in React Components using MongoDB and passing a Key: TypeError - Property _id is undefined

I've encountered an issue when trying to pass a field from MongoDB into a React Component. Here is the snippet of code I'm working with: import React from 'react'; import ReactDOM from 'react-dom'; import { Meteor } from &apo ...

Tips for clearing a material-ui search input field with the help of a button

Currently, I am working on a tutorial that involves implementing react material-ui tables along with a search input textfield. I am attempting to enhance this by adding a button that not only resets the table report but also clears the search input textfie ...

Tips for managing content and tables that exceed their container's boundaries

On my webpage, I have a slide-out sidebar that shifts the other contents and causes overflow with a scrollbar. I want the content to remain inside the window and adjust according to the available space. Image of Slide-out Sidebar As seen in the image, t ...

Displaying advertisements on a Vue.js element

It's a known issue that if we include the <script> tag in the "el" of Vue.js, an error will be displayed. This prevents me from being able to include any ads in the Vue "el" section. For example: new Vue({ el: '#app', data: { ...

Is there a way for me to directly download the PDF from the API using Angular?

I'm trying to download a PDF from an API using Angular. Here's the service I've created to make the API call: getPDF(id:any) { return this.http.get( `url?=${id}`, { responseType: 'blob' as 'json', obs ...

Javascript - Converting a function to run asynchronously

Just starting to work with Node.js for the first time and feeling a bit puzzled by asynchronous functions. I'm getting better at identifying when async is causing issues, but still unsure how to fix them. Here's the code snippet in question: fu ...

Backup files from OpenShift MongoDB

I've developed a scalable application in OpenShift using MongoDb2.2 and NodeJs0.10, Unfortunately, I am unable to utilize Cartridge rockmongo-1.1 as it cannot be integrated into the scalable application, What is the best way for me to retrieve my da ...

Tips for transferring information to a node server

Currently, I am working with Express and facing the challenge of dynamically sending data to the app.get() method. Specifically, on my index page, there is a list of topics, and upon clicking one, I need to send the name of that element as the required dat ...

"Using AngularJs, discover the best method for redirecting to a specific state based on a flag

When the userAccess flag in the controller is false, I want to hide all application content from the user and redirect them to access.html which includes a required access form. However, when using the code below, an error transition superseded is thrown. ...

jQuery: Modifying tags is a one-time deal

I am trying to create a feature where a <p> tag becomes editable when clicked. However, I am encountering an issue - it can only be edited once. Upon a second click, an error message appears in the console. You can view the fiddle demonstrating this ...

Using React to retrieve data from Firebase through axios

I recently uploaded some mp3 files to my Cloud Storage on Firebase. To retrieve these files, I am utilizing axios for the necessary operations. After modifying the permissions under the "rules" tab to: allow read, write, request; I am still encou ...

Express/NodeJS encountering a CORS problem, causing services to be inaccessible in Internet Explorer

Currently, I am working on a REST-based service implemented in Express/NodeJS. The code includes CORS (Cross Origin Resource Sharing) implementation to allow services to be consumed from browsers like Chrome and Firefox. However, there seems to be an issue ...

Expanding and collapsing a single item in a ListView with React Native

I am currently encountering an issue with my list of Messages, where clicking on any message expands or collapses all messages instead of just the individual message clicked. See the code snippet below for more details on how each Tab Component is populate ...

Understanding Three.js Fundamentals: Resolving GLTFLoader Animation and Variable Not Found Issues

My understanding of JS is very basic. After exploring the three.js docs on Loading 3D models, I managed to successfully render a 3D object and center it: const loader = new GLTFLoader(); loader.load( 'Duck.gltf', function ( duck ) { con ...

Preventing multiple tabs in a form with PHP

I have successfully used JavaScript to prevent a link from being opened in multiple browser tabs every time a user clicks on it. For example, if the destination of my link is Google, it will create a new tab if one does not already exist but refresh the ex ...

Problems encountered with nested AJAX calls and the $.when.apply function handling deferred promises efficiently

I am attempting to create a triple nested series of AJAX calls, as shown in the basic structure below (fail calls have been omitted). Progress is being made up to the second level with the eventCalls. The final when.apply.done only triggers after every si ...

Tips for managing the State with AppContext()---Need help figuring out how to handle

Why does setting the state userHasAuthenticated to true in the login function result in isAuthenticated being logged as false (staying the same in App.js as well)? Also, when trying to use it in the Home Component, it still shows false. //-------------- ...

Developing uniform resource locators with jQuery

As I work on developing my webapp, I have made use of the tag in my JSPs to ensure that all links within the application - whether they lead to pages or resources like images and CSS - always stem from the root directory rather than being relative to the ...

Angular checkbox is not syncing with the model

I am facing an issue in my code where the input is not properly binding to the checkbox. In my controller, I have defined a member variable like this: $scope.sameOptionsOnReturn = true; And in my view, I have set up the checkbox as follows: <input ty ...