Contrasting the characteristics of two distinct loops

After completing an exercise, I found the correct solution below. However, my initial solution did not work and I'm trying to understand why.

The only difference was in this line of code:

 for (var i = contacts.length; i > 0; i--) {

I am curious as to why reversing the direction did not produce the same result?

for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName == name){
        if (contacts[i].hasOwnProperty(prop)){
            return contacts[i][prop];
        } else{
            return "No such property";
        }
    }
}
return "No such contact";

Answer №1

Your code is facing multiple issues that need to be addressed.

  • One issue is that you initialize i = contacts.length, but remember that arrays start at index 0 and go up to array.length-1. To fix this, update your initialization to var i = contacts.length - 1.
    This change will resolve the first problem.
  • Another problem is that your loop does not reach the first element of the array because the stop condition is set as i > 0. To ensure the loop includes the first element, adjust the stop condition to i >= 0.
    Changing the stop condition to i >= 0 will solve the second issue.

Answer №2

Both loops have varying ranges.

If contacts.length was equal to 4, then the variable i would have iterated through these values:

console.log('ascending loop');
for (var i = 0; i < 4; i++) {console.log(i);}
console.log('descending loop');
for (var i = 4; i > 0; i--) {console.log(i);}

Answer №3

Starting index of an array is 0. However, the length starts from 1.

For example, if we want to access the last element in the contacts array:

let contacts = ['john','mary','susan'];
console.log(contacts[length-1])

In this case, the console won't display anything. Why? Because when you're trying to access the last element, you should always subtract 1 from the length of the array.

Answer №4

In the solution, the counter progresses from 0 to n, while in your loop, it goes from n to 1.

As a result, the index in your code never reaches 0.

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

Incorporate validation features within a jQuery method

I am struggling with some HTML and jQuery code that generates links based on user input. HTML <input type="text" id="text" placeholder="Enter text" autofocus /> <a id="link1" class="btn btn-info" href="#" target="_blank"> Search 1 </a> ...

When tab switching occurs, the alert box fails to be processed by the browser

When using the alert(message) function, it will display an alert box with a message and an OK button. It will also pause the execution of any code that follows until the OK button is clicked. However, I have noticed a peculiar situation where switching tab ...

The function getComputedStyle(elem).getPropertyValue('fontSize') returns incorrect values when the font size of the element is specified in em units

My current issue involves trying to obtain the font size of an element in the following manner: getComputedStyle(MyTargetElement , "").getPropertyValue('font-size') The result is coming back as 16px, when it should actually be 14px. W ...

"Encountered a problem while setting up the Mailgun webhook to handle both multipart and URL encoded

I have been working on creating a web hook listener for Mailgun, and I encountered an issue when I realized that Mailgun can post webhooks using either multipart or x-www-form-urlencoded content-types. Currently, my code uses Multer to handle multipart b ...

Enhancing MeshStandardMaterial in three.js with ID Color mappings

I am interested in incorporating color ID maps into three.js, inspired by the method found in Substance Painter: https://www.youtube.com/watch?v=5GqeyuZGOhc The desired outcome involves compositing the color map with the MeshStandardMaterial, followed b ...

Monitor changes in the ID attribute and ng-model using $watchCollection

My goal is to utilize the $watchCollection feature in my directive to monitor two specific elements. The first element is the ng-model. The second element is the id attribute. I have successfully implemented separate watches for each of them. retur ...

Plotting only the initial and final point on Google Maps using API

I am currently working on a tracking application that utilizes the Geolocation and Google Maps API. The app is set up to track the user's position using the watchPosition() function. As of now, a new blue icon is displayed every time a new longitude a ...

What is the best way to align table headers with their respective content?

Ensuring proper alignment of table columns with their respective headers is crucial. Consider an array of headers: const titles = ['name', 'lastname', 'age'] When displaying the table, the content may be like this: const cont ...

Tips on consolidating a loop query into a single query in PHP

I need assistance refining this code snippet. While it currently functions, making repeated MySQL queries isn't optimal. Can someone suggest a way to consolidate it into a single query? $unique_string = 'Unique string'; $number = count($ ...

If you invoke functionA within functionB, will functionA be called? How does this affect the compilation process?

I've been diving into the "You Don't Know JS" book series and came across a confusing piece of code. While looking at the following code snippet, I noticed that when I tried running it, nothing was printed out. Despite having "foo()" inside the f ...

Having trouble setting a background image for a specific DIV element in HTML

I am in the process of updating my webpage, and need some assistance implementing a small background image. Here is what I have done so far: https://i.sstatic.net/nTxtD.png Below is the marked section where I am trying to add the background image: https ...

What is the process for refreshing HTML elements that have been generated using information from a CSV document?

My elements are dynamically generated from a live CSV file that updates every 1 minute. I'm aiming to manage these elements in the following way: Remove items no longer present in the CSV file Add new items that have appeared in the CSV file Maintai ...

Problem encountered with the JavaScript for loop failing to execute consistently on each iteration

Currently, I am working on a JavaScript code that alerts the count in an array of pages. The variable urls represents an array of page names, while count contains the count value. My goal is to alert the count value for each page in the urls array. Howe ...

Encountering a popup_closed_by_user error while attempting to test Google OAuth within my web application

Currently, I am working on integrating Google login into my web application using AngularJS. Whenever the popup opens up for logging into my Google account or selecting an existing account, I encounter an issue where the popup closes with an error message ...

What could be the reason behind the disruption in this JavaScript associative array?

I'm facing an issue with my associative array, which I have confirmed through console.log to be initially: this.RegionsChecked = {"US":true,"APAC":true,"Canada":true,"France":true,"Germany":true,"India":true,"Japan":true,"LATAM":true,"MEA":true,"UK": ...

Is there a way to deactivate the minutes input feature in the Angular UI Timepicker?

I am using a plugin that displays the time in hours and minutes. However, I only need to show the hours. Is there a way to hide the minutes block? This is my HTML code: <uib-timepicker ng-model="mytime" ng-change="changed()" hour-step="1" minute-step ...

Tips for applying a jQuery class when the page is both scrolled and clicked

As I work on building a HTML website, I encountered an interesting challenge. I want to create a dynamic feature where, as users scroll through the page, certain sections are highlighted in the navigation menu based on their view. While I have managed to a ...

Issue with req.user being Undefined in Node, Express, Passport, and Mongoose

I've encountered an issue where req.user is defined when logging in, but undefined on other paths. I'm starting to feel stuck and out of ideas at this point. Another thing is that deserialization is never being called. server.js: var LocalStra ...

Ways to activate a stylish pop-up box using an input field (when focus is removed)

While attempting to activate Fancybox upon the user shifting focus away from an input field containing a value greater than 25, everything seems to be in order with the focus out and value checking code. Nevertheless, when Fancybox is triggered, the follow ...

Enhance the "content switcher" code

I have been working on improving my "contenthandler" function. It currently changes different articles when I click different buttons, which I am satisfied with. However, I believe there may be a better approach to this and would appreciate any advice on h ...