JavaScript: The length property of array[index] appears as undefined, despite displaying in the function

Learning JavaScript has been quite the adventure for me, but I can't seem to wrap my head around why I'm encountering an error on line 6 (specifically, 'cannot read property "length" of undefined) even though the length of each word in the index is printing correctly below it.

function findShort(s){
  var input = s.split(' ');
  var finalLength = 100;
  for (var i = 0; i <= input.length; i++) {
    if (input[i].length <= finalLength) {
      console.log(input[i].length);
      finalLength += input[i].length;
    }
  }
  return finalLength;
}

findShort("this is a test");

As a result of this code snippet, I'll get:

// -> 4
// -> 2
// -> 1
// -> 4
// -> TypeError: Cannot read property 'length' of undefined
    at findShort:6:16
    at eval:14:1
    at eval
    at n.<anonymous>

Answer №1

The reason for this issue is that you are exceeding the bounds of your array. It's important to iterate until you reach the length, not go beyond it.

function calculateShortestLength(s){
  var inputArray = s.split(' ');
  var shortestLength = 100;
  for (var i = 0; i < inputArray.length; i++) { // < not <=
    if (inputArray[i].length <= shortestLength) {
      console.log(inputArray[i].length);
      shortestLength += inputArray[i].length;
    }
  }
  return shortestLength;
}

calculateShortestLength("this is a test");

Answer №2

Your system has detected an issue. Please attempt the following code:

for (let i = 0; i < inpt.length; i++)
as your indexation appears to be lower than inpt.length

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

To ensure the next line only runs after the line above has finished executing, remember that the function is invoked in HTML

my.component.html <button (click)="refresh()">Refresh</button> my.component.ts refresh() { let self = this; self.isRefresh = true; //1st time self.getfun().then(() => { self.isRefresh = false; ...

Is it possible to exchange code among several scripted Grafana dashboards?

I have developed a few customized dashboards for Grafana using scripts. Now, I am working on a new one and realizing that I have been duplicating utility functions across scripts. I believe it would be more efficient to follow proper programming practices ...

Count the number of checkboxes in a div

In my current project, I am working on incorporating three div elements with multiple checkboxes in each one. Successfully, I have managed to implement a counter that tracks the number of checkboxes selected within individual divs. However, I now aspire to ...

Preserving text input with line breaks in a MERN Stack application

Can you help with saving multiple paragraphs in MongoDB? I have a textarea where users can input multiple paragraphs, but the line space is not being saved correctly in the database. Here is how I want the submitted data to look: Lorem ipsum dolor sit am ...

RS256 requires that the secretOrPrivateKey is an asymmetric key

Utilizing the jsonwebtoken library to create a bearer token. Following the guidelines from the official documentation, my implementation code appears as below: var privateKey = fs.readFileSync('src\\private.key'); //returns Buffer let ...

Displaying Live Data to Users on Rails 3 using Node.js and MongoDB

I am experiencing an issue with my Rails web application where the data is not being displayed in real-time to users. Despite having a node.js server that is continuously updating a cloud database accessible by the Rails app, the data does not appear insta ...

Creating a sorting function in VueJS requires a few key steps

I'm working on implementing a sorting function in my VueJS code that includes the following options: Price: Low to High, Price: High to Low. Here is my template: <div name="divSortBy"> <span> Sort by: & ...

Filtering deeply nested arrays

Hey, I'm working with this interesting array: [ { "Navn": "Long Island Iced Tea", "Nummer": "2", "Glas i ml": "250", "Instruktioner": "", "a": "Hæld is i glasset", "b": "pynt med en skive lime", ...

Strange Actions with JQuery Drag-and-Drop Functionality

Apologies for my limited experience with JQuery UI, but I am in the process of creating a web-based chess engine for 2 players using JavaScript. Instead of point and click, I have decided to implement a user-friendly drag and drop feature for non-mobile us ...

Is there a way to effortlessly scroll an element when the CSS overflow property is designated as auto?

I need help with creating a testimonial section where two divs automatically scroll inside a fixed-height container. Currently, only one div is scrolling while the other remains static in my code. I have implemented JavaScript for automatic scrolling wit ...

How can I ensure that the scripts returned in HTML via AJAX are executed when using $.load()?

I have been trying to make an AJAX call and receive a partialView which contains some script that needs to be executed. I did some research and learned about the "eval" method, but then discovered that the $.load() method should handle this for me. Howeve ...

Identifying the modifications made to a Firestore list, including additions, deletions, and changes

Utilizing Firestore as the backend has allowed me to navigate basic crud methods effectively. However, I am curious about how to identify changes within a list of returned items after the initial subscription. My goal is twofold: - Minimize the number of ...

Include a Class into a label using jQuery

I am having an issue where I need to specifically add the error class to a <label> with the name attribute set to choice_16_0. However, when I try to achieve this using my code, it ends up changing all labels on the page to <label for="choice_16_0 ...

Tips for concealing a div when the mouse is moved off it?

My goal is to create a simple hover effect where hovering over an image within a view filled with images displays an additional div. This part works as expected. However, I'm facing issues when trying to hide the same div when the user moves out of t ...

Can you explain why the .js code is causing such high CPU usage in popular video players?

Why is the .js code running continuously even when the video is paused and there is no user interaction? I observed this phenomenon on a Windows 10 Atom Tablet, particularly when in energy-saving mode. The CPU usage for video playback and decoding almost ...

Receiving a 401 error while attempting to make an axios get request with authentication headers

I have been utilizing axios in my React project to fetch data from MongoDB. However, I am facing a challenge with the axios get requests returning a 401 error when I include my auth middleware as a parameter. This middleware mandates that the user must pos ...

Generate Bootstrap 5 Navbar <li> and <ul dropdown item> dynamically using JavaScript

Requesting assistance I have stored text in the constant.js file as shown below. export const navLinks = [ { id: "manage", title: "Manage", }, { id: "transactions", title: "Tran ...

Issues are arising with back4app's cloud code due to an invalid function being

My current challenge involves implementing a payment system in an iOS app using Conekta. Previously, everything was working smoothly with Braintree in the cloud code on Back4App, but after switching to Conekta, the Back4App calls keep failing with an "Inva ...

Utilizing Angular's global interceptor functionality can streamline the process

Having trouble making 2 interceptors (httpInterceptorProviders, jwtInterceptorProviders) work globally in my lazy modules. I have a CoreModule and X number of lazy-loaded modules. Interestingly, autogenerated code by the Swagger generator (HTTP services) g ...

How can you use ng-click to re-sort data that has already been loaded using Angular's ng-click?

I'm having trouble switching between loading and sorting the information in the table using ng-click. The functions to load and sort work correctly individually, but I can't seem to switch between the two. It seems like I reset the countries data ...