Error: Unable to access the 'length' property of an undefined value | Solving the challenge of finding the shortest word within a string | Codewars Problem

I'm currently working on a function to find the shortest word in a given string of words.

Issue: I encountered the error below

TypeError: Cannot read property 'length' of undefined at findShort at Test.describe._ at /runner/frameworks/javascript/cw-2.js:152:11 at Promise._execute at Promise._resolveFromExecutor at new Promise at Object.describe at /home/codewarrior/index.js:24:10 at /home/codewarrior/index.js:28:5 at Object.handleError

Below is the code snippet in question

findShort("turns out random test cases are easier than writing out basic ones");

function findShort(s){

  let array = s.split(" ");
  let shortestWord = array[0];
  
  for (i = 0; i < array.length; i++) {
    let str = array[i + 1];
    
    if (shortestWord.length > str.length) {
      shortestWord = str.length;
    }
    
  }
  
  return shortestWord;
}

Answer №1

Upon review, I have identified two issues:

  • The line let str = array[i + 1] may return undefined during the final iteration of the loop when i is equal to or exceeds the array length. To address this, consider adjusting the loop condition to i < array.length - 1.

  • Additionally, the current implementation assigns the word's length to the variable shortestWord, instead of the word itself as intended.

To incorporate these modifications, you can update your code as follows:

function findShort(s) {

  let array = s.split(" ");
  let shortestWord = array[0];
  
  for (i = 0; i < array.length - 1; i++) { // Adjusted loop condition to prevent out-of-bounds access.
    let str = array[i + 1];
    
    if (shortestWord.length > str.length) {
      shortestWord = str; // Correctly assigning the word to the variable.
    }
    
  }
  
  return shortestWord;
}

const result = findShort("turns out random test cases are easier than writing out basic ones");
console.log(result);

Answer №2

Here is a more streamlined solution to achieve the desired outcome:

console.log(findShortestWord("turns out random test cases are easier than writing out basic ones"));

function findShortestWord(sentence){
  let input = sentence;
  let wordsArray = input.split(" ");
  
  var shortestWord = wordsArray.reduce((shortest, current) => {
    return current.length < shortest.length ? current : shortest;
  }, wordsArray[0]);
  return shortestWord;
}

Link to JSFiddle Demo

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

Unique Text: "Personalized marker/pin for interactive map feature"

Looking to create a custom image map marker/pin with a unique bottom design resembling a union shape using CSS and Vue.js. I've attempted it myself but haven't been able to achieve the exact look as shown in the reference image. Any advice or ass ...

Error: React js app has crashed. Currently waiting for file changes before restarting

I recently began using nodemon and started working on a small sample project. However, when I try to launch the server using sudo npm run dev, I encounter the following error: [nodemon] app crashed - waiting for file changes before starting... The error ...

Issue encountered while attempting to create entity in jhipster

After executing the creation of an entity in the command line, JHipster successfully generated Java and script files but encountered issues with updating the database. No new table was inserted despite starting MySQL and turning off the application befor ...

Using React's useEffect and useContext can cause issues with certain components, particularly when dealing with dynamic routes

Currently, I am developing a React blog application where posts are stored in markdown files along with metadata in Firestore. The content .md files are saved in Cloud Storage. In the App component, I utilize useEffect to retrieve the metadata for each pos ...

Transforming a JavaScript component based on classes into a TypeScript component by employing dynamic prop destructuring

My current setup involves a class based component that looks like this class ArInput extends React.Component { render() { const { shadowless, success, error } = this.props; const inputStyles = [ styles.input, !shadowless && s ...

Attempting to extract decibel levels from an audio file using JavaScript

I've been exploring the details provided here: Is there a way get something like decibel levels from an audio file and transform that information into a json array? However, when attempting to execute the JSBin snippet below, I encountered some conf ...

Undefined Response Error when Utilizing Dropzone for File Upload in Express

I am currently in the process of setting up a basic image upload demonstration using Dropzone and Express. Here is what my form looks like: <form id="ul-widget" action="/fileupload" class="dropzone" enctype="multipart/form-data"> <div class="fal ...

Having trouble getting a basic jQuery UI tooltip to function properly

I attempted to recreate the demo found on this website: http://jqueryui.com/tooltip/#default Here is the HTML code I used: <h3 title='this is the title of hello world'>hello world</h3> And here is the JavaScript code: $(document). ...

Display a preview of a React component

Currently facing a challenge where I need to create a form for users to adjust the title, background color, button background, text color, and other settings of a component. I want to provide a live preview of the component as the user makes changes. I en ...

Is there a way to temporarily toggle classes with jQuery?

Incorporating ZeroClipboard, I have implemented the following code to alter the text and class of my 'copy to clipboard button' by modifying the innerHTML. Upon clicking, this triggers a smooth class transition animation. client.on( "complete", ...

Enforce the splicing of the ng-repeat array with the utilization of track by

Our app incorporates a task list that can potentially grow to a substantial size. The main task list is accompanied by a sidebar, where selected tasks can be edited using a different controller (TasksSidebarCtrl instead of TasksCtrl which handles the list ...

Creating multiple unique custom attributes for a specialized HTML element

Creating getter/setter methods for a custom attribute on a custom HTML element is quite simple: customElements.define('custom-el', class extends HTMLElement { static get observedAttributes() { return ['customAttr'] ...

Utilize Vue.js functions within data through the Vue.js context

I'm trying to incorporate a function as a data property. While it works for the 'works' data property, I need access to the this context within the function in order to calculate values from the shoppingCart property. Is there a way to achie ...

Adding several <div> elements with the correct indices

I need help with a dynamic form that requires users to select a state before revealing the corresponding cities within that state. <form method="post"> <div class="summary"> <div class="trip"> <select name="State" class="s ...

Loading javascript libraries that are contained within an appended SVG document

I am currently working on developing a browser-based SVG rasterizer. The unique aspect of this project is that the SVG files may contain JavaScript code that directly impacts the output, such as randomly changing element colors, and utilizes external libra ...

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

What is the best way to access the next-auth session using getStaticPaths and getStaticProps in dynamic routing scenarios?

I am currently working on implementing dynamic routing in a NextJS application. I need to retrieve the token from next-auth in order to make axios requests to an API and fetch data from getReport and getReports (located in /reports.js). However, I am facin ...

Deactivating a button if the input fields are blank using ReactJS

Hi there, I'm new to reactJS and recently encountered an issue with my code. Everything seems to be working fine except for the NEXT button not being disabled when text fields are empty. My expectation is that the NEXT button should only be enabled af ...

JS glitch leading to oversized window dimensions - Issue with dropdown menu

I recently integrated a dropdown into my website using Foundation CSS. To see the dropdown in action, you can login with the credentials provided (username: stackoverflow password: testtest) on . However, I noticed that when logged in, the page on the rig ...

Leverage JavaScript to retrieve the number of active Ajax requests in JSF

When running Selenium tests using JS, I want to ensure that there are no active Ajax requests. While I can successfully extract the amount of active Ajax requests for jQuery and PrimeFaces, I am facing some issues with JSF. String jsPF = "return PrimeFace ...