How can I eliminate the occurrence of "undefined" during the initial iteration of my for loop that iterates over an array?

How can I prevent getting 'undefined' as the last output when using console.log() with a looping construct?

let array = ["Fiji", "Santorini", "Bora Bora", "Vancouver"];
let arrayLength = array.length;

for(let index = arrayLength; index >= 0; index--)
{
    console.log(array[index]);
}

Resolved by updating:


let arrayLength = array.length - 1

index >= 0;

Answer №1

In response to @Pointy's observation, it's important to note that the "greater equal" operator in JavaScript is represented as >=, not =>. Additionally, it is essential to initialize the index variable as let index = arrayLength-1 since JavaScript indexes start at 0, making the index of the last item in the array one less than the length of the array. The corrected code snippet is as follows:

let array = ["Fiji", "Santorini", "Bora Bora", "Vancouver"];
let arrayLength = array.length;

for(let index = arrayLength-1; index >= 0; index = index - 1)
{
    console.log(array[index]);
}

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

Nested ng-repeat using td to display multiple items in AngularJS

I am having an issue with the code as it is producing a table with the elements all in a single column. Below is an example of the data: var data = [[{"id":"1","value":"One"},{"id":"2","value":"Two"},{"id":"3","value":"three"}],[{"id":"4","value":"four"} ...

Convert a list into a hierarchical structure of nested objects

Working with angular, I aim to display a nested tree structure of folders in an HTML format like below: <div id="tree"> <ul> <li ng-repeat='folder in folderList' ng-include="'/templates/tree-renderer.html'" ...

The function _path2.default.basename does not work when using convertapi within an Angular framework

I'm currently working on integrating the convertapi into my Angular 11 application by referencing the following documentation https://www.npmjs.com/package/convertapi My goal is to convert PDFs into images, However, I encountered an issue when tryi ...

Angular route unable to detect Passport User Session

The navigation bar in the header features buttons for Register, Login, and Become a Seller. Upon user login, it displays logout and view profile buttons. This functionality is operational on all routes except one, causing a client-side error. user not def ...

Having trouble accessing information from a JSON file

Currently, I'm working on a project where I need to read data from a JSON file. However, I encountered an issue. The data I'm getting when I try to read it doesn't match the content of my file pliki.json. pliki.json: [ { & ...

Javascript enables dynamic field addition to tables

I have JSON data that needs to be displayed in an HTML table. To input the values, I have individual fields for firstname, lastname, email, and phone number, along with an "Add Row" button. When I click the "Add Row" button, I want the entered values to b ...

Creating a loading component using the power of the useEffect hook

One of the components I've been working with is a loading bar that can be easily imported like this: import { CircleToBlockLoading } from "react-loadingg"; I tried using it in the following way, but it doesn't seem to render anything: ...

Is it necessary for the key in JSON syntax to be enclosed in quotes?

I am facing an issue with converting a specific string to JSON format. Here is the string: '{clientId: "1239268108.1505087088", userId: "0.4744496956388684", "url": "http://boomfix.es/", "pageUrl": "1", "timer": "15", "clickCount": "4", "mouseMax": " ...

How can you turn consecutive if statements into asynchronous functions in JavaScript?

In my code, I have a loop with a series of if statements structured like this: for( var i = 0; i < results_list.length; i++){ find = await results_list[i]; //result 1 if (find.Process == "one") { await stored_proc(38, find.Num, find ...

Angular causing WKWebview to freeze

Situation Our Angular+Bootstrap app is functioning smoothly in Desktop on all operating systems, as well as Android and iPhone devices. There are no visible JavaScript errors or CSS warnings. Dilemma However, an issue arises intermittently while using t ...

What could be causing the form DOM object values to not update in this specific instance?

I'm currently using JavaScript to create a password checksum by utilizing the SubtleCrypto.digest() function. This function produces the result as a promise object, which is then fed into an inline function to convert the outcome to a text representat ...

Information is not transferring to Bootstrap modal

I attempted to send a value to a modal by following the instructions on the Bootstrap documentation here. However, I am facing an issue where the data is not being successfully passed. To trigger the modal, use the following button: <button type=" ...

What sets xhr.response apart from xhr.responseText in XMLHttpRequest?

Is there any difference between the values returned by xhr.response and xhr.responseText in a 'GET' request? ...

Facing challenges in implementing a logic to showcase an intricate page on express.js (node.js) platform

Having trouble setting up a functional logic to display a detailed page showcasing the post title, image, and details. Currently, I've successfully created a list page that displays all the posts by the logged-in user with the title, image, and detail ...

How can the checkers code be corrected due to a mistake?

Designed a simple game where the objective is to clear all the pieces by jumping over the checkers. However, encountering an error when attempting to remove the checker for the second time. Uncaught TypeError: Cannot read property 'theRow' of u ...

Eliminating an element from an object containing nested arrays

Greetings, I am currently working with an object structured like the following: var obj= { _id: string; name: string; loc: [{ locname: string; locId: string; locadd: [{ st: string; zip: str ...

Transform an Angular application built using the Meteor framework to an Express JS-Angular application

Is there an automated or minimalist way to transform an application with a meteor backend and angular frontend to use a backend in Express js and keep the frontend using vue js instead? I have not been able to find any resources or documentation that prov ...

Tips for organizing date columns in Bootstrap-Vue when utilizing a formatter for presentation purposes

I am working with a table containing date objects, and I have transformed them for display using the following code: { key: "date", formatter: (value, key, item) => { return moment(value).format("L"); }, sortable: true } However, this ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

Encountering an issue when trying to generate a button in Angular

I am currently using JavaScript to dynamically create a button in Angular. While I have been successful in creating the button, I am encountering an error when attempting to change the classname. The error message I am receiving is: Property 'clas ...