Error: Unable to access the length of an undefined property

var areYouReady = prompt("Are you prepared for this task?").toLowerCase();
var starting_DescriptionStart;
var starting_DescriptorOfThing;
var starting_Thing;
var starting_DescriptionEnd;

if(areYouReady === "begin"){
//Start the process

 starting_DescriptionStart = ["You encounter a"];

 starting_DescriptorOfThing = ["Huge", "Tiny", "Red", "Blue", "Green", "Black", "White", "Invisible", "Camo", "Striped", "Breathing", "Living", "Sentient"];

 starting_Thing = ["Box", "Dragon", "Lion", "Eagle", "Tiger", "Vampire", "Dagger", "Bracelet", "Ring", "Tiara", "Stack of books", "Fox", "Cat", "King", "Witch", "Elf", "Magician", "Table", "Mustard"];

 starting_DescriptionEnd = ["that is trying to harm you.", "at the beach.", "on social media.", "in a haunted house.", "at a carnival.", "below ground.", "high up in a tree.", "at a fancy party.", "outside."];

// Generate random numbers 
var randomNumber1 = parseInt(Math.random() * starting_DescriptionStart.length);
var randomNumber2 = parseInt(Math.random() * starting_DescriptorOfThing.length);
var randomNumber3 = parseInt(Math.random() * starting_Thing.length);
var randomNumber4 = parseInt(Math.random() * starting_DescriptionEnd.length);
generatedSituation = starting_DescriptionStart[randomNumber1] + " " + starting_DescriptorOfThing[randomNumber2] + " " + starting_Thing[randomNumber3] + " " + starting_DescriptionEnd[randomNumber4];

alert(generatedSituation);


}else if(areYouReady === "add description start"){
//Allow user to add a new descriptor
var s_DescStart = starting_DescriptionStart.length + 1;

var inputA = prompt("What do you want to incorporate into the introductory description?");

starting_DescriptionStart[s_DescStart] = inputA;

alert(starting_DescriptionStart[1]);
}

I am working with this piece of code, which can be easily expanded by adding elements to the arrays. However, I am looking to create a system where users can contribute to it and then execute the updated version.

After attempting to add new descriptions and encountering an error message when running the program:

Uncaught TypeError: Cannot read property 'length' of undefined

I'm puzzled as to why it's indicating that the variable is undefined, considering it should be globally accessible.

Answer №1

Within your code's 'else if' block, the variable starting_DescriptionStart is not being initialized or defined, which causes it to remain undefined and without a length.

To resolve this issue, ensure that you declare and assign a value to starting_DescriptionStart at the beginning of your code, rather than solely within the 'if' statement.

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

Getting the autogenerated document ID from Firestore - A Step-by-Step Guide

When creating my document, I rely on the auto-generated ID. However, after setting it, I find that the retrieved ID is different from the one in the Firestore Database. await admin.firestore().collection("mycollection").doc().set(mydata) .then(doc = ...

Troubleshooting event binding problems with jQuery

<div id="parent"> <div id="children"> </div> </div> If we attach the same events to both parent and children elements: $("#parent").live({ mouseenter : Infocus , mouseleave : Outfocus }); $("#childre ...

Implement a click event to trigger a search functionality within Bootstrap

I have implemented the following code to add search options in the navigation bar. It is displaying correctly, but I am not getting the click action that I require. For example, I want to trigger an action from JavaScript when the user clicks on the enter ...

What could be causing the ajax request to not go through?

Check out this function I created that triggers an event when any inputs in an HTML form are changed. Function Snippet: function customEvent(form, element) { var timer; $(element).keyup(function () { clearTimeout(timer); if ($(ele ...

The hamburger menu is not functioning properly online, but it works perfectly in xampp/localhost

I'm currently facing a challenge with my responsive menu. It works perfectly on my offline server in mobile format, but as soon as I upload it to the real server, it stops working. I've been grappling with this problem for hours. Here's the ...

Ways to select the nearest element within a designated class

I am attempting to find the closest or nearest class of a specific element. How can I achieve this? I am currently utilizing the .closest method. HTML <div class="test">.test</div> <!-- Not this --> <div> <div class="test ...

There seems to be an issue with the Node JavaScript file not updating automatically

Currently facing an issue while trying to develop my first node application. The problem lies with the JavaScript file, as my CSS file is working fine which is causing confusion for me. Here is a snippet of my app.js code: var express = require("express") ...

Error with React's thumbnail component

After integrating the thumbnail component into my project, I encountered an error which is displayed in the image below: https://i.sstatic.net/DGlXZ.png I am seeking assistance with understanding the issue by providing the code from my webpack.config.js ...

Tips for transferring form data from a React frontend to the backend Node.js server

I have been attempting to send FormData from React JS to my backend (Express Node server) with the code snippet provided below. However, I am encountering an issue where req.body.myFormData in expressTest.js is showing up as empty. Despite trying various ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

In a multi-line chart, learn how to efficiently toggle the visibility of data points and lines

My goal is to toggle data points in my line chart by clicking on the legend. You can view my code here. Currently, when I click on the legend, the lines and corresponding axis are toggled on and off successfully, but the data points do not change. Below is ...

Having issues with Tailwind colors not dynamically updating in brackets

Recently, I encountered an issue where my custom colors were not working when implemented dynamically. Below, you'll find two sets of codes and screenshots: one with the dynamic code and output, and another with the static code and output. I prefer n ...

The clash between Traditional JavaScript and jQuery

As I pored over a textbook, I found myself stumped by an example problem. Here is the HTML code in question: $(function(){ $("#checkAll").click(function(){ $("[name=items]:checkbox").attr("checked", true); console.log("check all"); }); $("#checkNo").cl ...

Font-awesome integration in Vue.js causing extremely slow hot reloading

Recently, I decided to embark on a fun project using Vue.js because working with this framework seemed enjoyable. To enhance my project, I chose to incorporate the https://github.com/FortAwesome/vue-fontawesome component. However, upon using it in one of m ...

Please ensure to log out when the user exits the tab

I am looking for a way to automatically log out users from my Django site when they close the browser tab or window. Ideally, I want users to be forced to re-enter their username and password if they try to access the site again after closing it without cl ...

Is there a better way to remove the hidden attribute from p2 since calling removeAttribute() doesn't appear to work?

Is there a way to successfully change the attribute of an object using removeAttribute to remove its hidden status? I've been attempting this but haven't had any luck so far. It seems like my code isn't having any effect. Could I be making ...

Using moment-duration-format in TypeScript: A step-by-step guide

In my TypeScript (Ionic2/Angular2) project, I have incorporated moment.js. After reading through this post, I decided to experiment with a plugin called moment-duration-format With the npm package and type definition installed, I can use it by importing a ...

API response in NodeJS encounters failure following fs.writefile operation

A new API has been developed to create a file and then request a log API after the file is written. The response will be sent back to the user based on the log API response. Here is a simplified version of the code: const express = require('express&a ...

Are there any distinctions between these two compact React components?

Let's compare these two components: function App1 () { return <button onClick={() => null}>Click me</button> } function App2 () { const fn = () => null; return <button onClick={fn}>Click me</button> } The on ...

Creating a function with a flexible number of parameters assigned to a variable:

When setting up a Socket.IO client, I have multiple methods structured like the following: myobject.prototype.A = function (callback) { this.foo('a', null, callback); } myobject.prototype.B = function (bar, callback) { this.foo('b&a ...