The `toString` function is displaying an array instead of the expected string

As a beginner in programming, I am currently enrolled in an introductory JavaScript course. However, I am facing an issue with my assignment where the toString method is printing an array instead of a string. Despite thorough research, I have been unsuccessful in finding a solution to this problem. The objective of the assignment is as follows:

To create a constructor function named World (note that constructors should start with a capital letter).

The World object must include a property called plan which consists of an array of strings.

Create a prototype method for World that displays the content of the array with line breaks between each element (using \n as the line break character)

Instantiate a variable named world and execute its toString method.

Below is the code snippet that I have developed so far:

function World(plan){
  this.plan = plan;  
}

var plan = ["––––––––––",
            "|   _    |",
            "|  |     |",
            "|__|     |",
            "| ___|   |",
            "––––––––––"];

var funWorld = new World(plan);

World.prototype.plan = function() {
    console.log(this.plan + "\n");
    return this;
};

World.prototype.toString = function() {
    return(this.plan);
};
console.log(funWorld.toString());

This is the current output that I am getting:

[
0:  "––––––––––"
1:  "|   _    |"
2:  "|  |     |"
3:  "|__|     |"
4:  "| ___|   |"
5:  "––––––––––"
]

I am uncertain about where I might have made an error. Any guidance or assistance would be greatly appreciated.

Answer №1

You are currently shadowing the prototype method plan, by having an instance property with the same name.

In your code, the toString method simply returns the instance property, which happens to be an array.

It seems redundant to have a separate plan method when the logic could just be contained within the toString function.

function World(plan){
  this.plan = plan;  
}

World.prototype.toString = function() {
    return this.plan.join('\n');
};

var world = new World(["––––––––––",
                      "|   _    |",
                      "|  |     |",
                      "|__|     |",
                      "| ___|   |",
                      "––––––––––"]);
                     
console.log(world.toString());

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

Converting large numbers (exceeding 53 bits) into a string using JavaScript

I have a REST service that returns JSON. One of the properties in the JSON contains a very large integer, and I need to retrieve it as a string before Javascript messes it up. Is there a way to do this? I attempted to intercept every response using Angular ...

Building a React component that's a table containing rows that can be scrolled and elements that are clickable

Imagine having a set of events and their respective participants: const myData = { "event_1": ["1", "2","3"], "event_2": ["11", "5","8", "9"], "event_3&quo ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

Why isn't my classList .add method working properly?

I've created a video slider background on my website, but I'm having trouble with the Javacript for video slider navigation. When I click on the button to change the video, nothing happens. The console is showing an error message that says "Canno ...

Sending radio button value via AJAX request

Greetings and thank you for taking the time to hear out my query. I am aware that this question has been asked numerous times before (as informed by SO) but my case is slightly unique. I currently have a functional AJAX script that utilizes a dropdown menu ...

Ideal JavaScript data structure for connecting three arrays

My goal is to establish a connection between three arrays in the following manner: arr1 = ['A', 'A', 'B', 'B', 'C', 'C' 'A', 'C'] arr2 = ['a', 'aa', ' ...

Sharing information between controllers in OnsenUI using AngularJS and PhoneGap

I've encountered similar questions to mine that have been addressed, but I believe my scenario is unique. I began with the sample code available on this page for a basic app featuring a sliding menu integrated with Google Maps. My current project inv ...

hitting the value of the text input

Is there a way to strike through only the first word in an input box of type text, without editing the html? I've tried using css text-decoration: line-through; but it's striking both words. Any suggestions on how to achieve this using javascript ...

What is the best way to provide a static file to an individual user while also sharing its file path

I have integrated jsmodeler (https://github.com/kovacsv/JSModeler) into my website to display 3D models. Currently, users can only select a file using a filepicker or by entering the path in the URL (e.g., http://localhost:3000/ModelView#https://cdn.rawgit ...

Create an array that can contain a mix of nested arrays and objects

Working on my project using Angular and TypeScript includes defining an array that can contain arrays or objects. public arrangedFooterMenu: IMenuItemType[][] | IMenuItemType[] = []; typesOfData.forEach(type => { let filteredData: IMenuItemType | ...

Just starting out with Ruby and hitting a roadblock with Diagonal Difference

Currently working on a coding challenge from HackerRank called Diagonal Difference. This is the code I've written so far: def diagonalDifference(arr) first = 0 second = 0 i=0 puts arr while i < arr.length first += arr[i][i] ...

Verifying internet connectivity and updating content using jQuery and JavaScript

Upon loading the page, the following functionality occurs without triggering a click event: The updated code attempts to determine if the internet connection is active. If the connection is off, the 'link' on the page will be disabled (non-click ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

Can the data retrieved from a jsonp call that may be considered "bad" be utilized effectively?

When making a JSONP call to another domain, I am receiving data that is in JSON format but not wrapped in a function. This causes a parse error to occur. However, the data is still retrievable and visible. Despite the error, is it possible to utilize the ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...

I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following. I have successfully executed the loop and managed to display it on my frontend desi ...

Tips for Using Threejs Loaders in a React App

Greetings and thank you for taking the time to read my question. ...

Handling an HTML Form without the Submit Button using VeeValidate

I've implemented a form handler using its composable feature in my <script setup>: const { submitForm, resetForm, handleSubmit, meta } = useForm() function save() { // Want to submit the form here submitForm() // Not working showSaveSnac ...

Attempting to retrieve information from my MongoDB database and populate it into a <table> structure on a web page

My objective is to extract data from a MongoDB database and display it in an HTML table. Specifically, I am trying to retrieve information from the hangman database's players collection, which contains fields for name and score. Can anyone help me ide ...

Customizing JqGrid to include a button in the advanced search dialog

I am interested in enhancing the advanced search dialog to include a feature that allows users to save a complex query they have built. Although saving the SQL code is not an issue, I need guidance on integrating buttons within the advanced search query d ...