Encountered an error while looping through an array of strings: TypeError - Unable to access property '0' of undefined

I have a collection of strings with varying lengths and I am trying to loop through all the arrays to find the LongestCommonPrefix. It's a problem on leetcode.com that seems relatively simple.


    let words = ["str", "string"];
    let longestLength = words[1].length;

    // Some elements at the 2nd level do not exist in the array
    for (let i = 0; i < longestLength ; i++) {
        console.log('typeof: ', i, typeof words[0][i]);
    }

    // The 3rd element of the array has not been initialized
    for (let i = 0; i < words[0].length + 1; i++) {
        try {
            console.log('typeof: ', i, typeof words[3][i]);
        } catch(error) {
            console.error('Error handled:', error.message);
        }
    }

After running this code snippet, the output is as follows:


    typeof:  0 string
    typeof:  1 string
    typeof:  2 string
    typeof:  3 undefined
    typeof:  4 Error handled: Cannot read property '0' of undefined

I'm unclear on why the first loop successfully iterates over the array and returns 'undefined', while the second loop (intentionally targeting element [3] which is undefined) throws an error. How can I prevent this runtime error?

Answer №1

When attempting to access a property that doesn't exist within an object, the result will be undefined.
However, if you try to access a property of null or undefined, you will encounter a type error.

If l[3] is undefined and you attempt to access property 0, you will receive an error. However, when l[0] is neither undefined nor null, you can freely access any existing properties which will return their values, or return undefined for non-existing properties (or ones explicitly set to undefined).

This behavior extends to primitives as well, as they are automatically promoted to objects in order to have access to properties.

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

JQuery is failing to parse JSON data

I've written a script to fetch data and display it in an HTML table. Here is the script: $('#search_filter_button').click(function (e) { e.preventDefault(); // Prevent form submission var county = $('#filter_county').val() ...

Using recycled frame buffers in a threejs fragment shader

I'm currently working on a project to develop an app that emulates the effect of long exposure photography. The concept involves capturing the current frame from the webcam and overlaying it onto a canvas. As time progresses, the image will gradually ...

JSON parsing partially successful: sub-object is empty

Attempting to parse a json file, my initial try with a simplified version was only partially successful. The simplified json structure resembles the following: { "rowCount": 102, "data": [ {"id": "56" ...

AngularJS dual-stage resolution for resolving dependencies

I am facing a scenario where I must resolve one item before obtaining the data necessary to resolve another: .state('addtrip', { url: '/addtrip', templateUrl: 'views/addtrip.html', controller: &a ...

Troubleshooting the issue: Difficulty in activating Navbar dropdown using Angular and ui-router

I've been struggling with this issue for some time now - trying to make a simple bootstrap navbar dropdown function properly with angular ui-router and ui-bootstrap (1.3.3, the latest version). Below is my current code: <div class="container"> ...

Can you explain the significance of `$array[x, y]` in Perl code?

It has come to my attention that @array[0,2,6] is an array filled with multiple values. My previous understanding was that $scalar=3 indicated a single variable holding one scalar value. But now I am puzzled about $array[3, 4]. Could it be a scalar varia ...

Incorporate PHP form and display multiple results simultaneously on a webpage with automatic refreshing

I am currently in the process of designing a call management system for a radio station. The layout I have in mind involves having a form displayed in a div on the left side, and the results shown in another div on the right side. There are 6 phone lines a ...

Sending data from a Parent component to a Child Component in Angular using the Pass API with an array return

Within this context, I am endeavoring to transmit the values of the bookingInfo array (assigned as this.bookingInfo = bookings.responseObj.txnValues;) to my child component. The current setting pertains to my parent component. @Component({ selector: &a ...

Update breadcrumbs dynamically by clicking on each horizontal panel

I've been dealing with a problem for the past 24 hours. I want to implement a horizontal accordion with breadcrumbs on a webpage. How can I achieve this dynamically, so that when a user clicks on any link in the accordion, the breadcrumbs update simul ...

jQuery: Remove the class if it exists, and then assign it to a different element. The power of jQuery

Currently, I am working on a video section that is designed in an accordion style. My main goal right now is to check if a class exists when a user clicks on a specific element. The requirement for this project is to allow only one section to be open at a ...

The function window.location.replace() unexpectedly results in the insertion of extra double quotation

I keep encountering an unusual issue where a double quote is being added to my HTML through my PHP script. Despite my attempts to resolve it, I am unable to find a solution. Here is the code snippet: <?php $Client_number =$_GET['client_number& ...

Troubleshooting: My Angular 2 Application is Unable to Perform HTTP

I've exhausted all options and I'm still unable to send an http request to my node server on heroku. I can access the route manually, so it's not an issue with the server. Below are snippets of my service and page: **Class is subscription.s ...

The issue of 'MessageChannel not defined' arises specifically on web pages that have implemented reCaptcha v2

I am currently working on scraping some websites that have implemented reCAPTCHA, but I keep encountering an error when loading the page's source: (node:15536) UnhandledPromiseRejectionWarning: ReferenceError: MessageChannel is not defined. Despite a ...

Exploring the method of implementing a "template" with Vue 3 HeadlessUI TransitionRoot

I'm currently working on setting up a slot machine-style animation using Vue 3, TailwindCSS, and HeadlessUI. At the moment, I have a simple green square that slides in from the top and out from the bottom based on cycles within a for-loop triggered by ...

Updating Documents in CouchDB

Can you please confirm if this is the correct method for updating a document in couchDB? To update a document (let's call it fooDoc), I must pass "_rev". First, I need to retrieve that document using the following code (foo.get). Then, in the callbac ...

Using Vuejs: incorporating imported plugin mixins locally

Can a mixin from a VueJS plugin be used in just one component? I made a plugin and noticed that once I import it, I can use the mixin's functions in all my components. Is there a method to restrict it to just one component, or do plugins inherently ...

What causes the page loading issue in Firefox when a cache manifest is used?

I recently created an HTML5 game that I wanted to make playable offline. To achieve this, I added a manifest file to the game directory. The game is located in a subdirectory at /games/game/, and the manifest file resides within that same directory at /ga ...

When using React Router with Suspense for lazy loading, my notFound page consistently displays beneath all of my components

I have a component that generates dynamic routes using a list called routes[], but whenever I add the route for the "not found" page NotFoundUrl, it always displays it in all components. All the other routes work perfectly fine, but when adding the 404 ro ...

Guide on loading '.obj' files with multiple '.mtl' files using Three.js

I am attempting to load the cube.obj file which references multiple cube_*.mtl files, each of which utilize texture images in the format *.png. The resources can be found here. My goal is to dynamically load objects with the same geometry but different mat ...

Checking the URL in Redux Form

I am currently using the redux-form library to manage my form in React Redux. I have successfully implemented validation for fields like email and name. However, I am facing an issue with validating a URL field in redux-form. What specific format should I ...