Why does an array return [object Object] upon any interaction, especially when it was returned from a class?

Introduction to SPA and Router

I am currently delving into the workings of single page applications, specifically focusing on routers, state management, routes, and more. I have successfully implemented a basic hash router that can display content on a fragment element. Now, I am attempting to introduce a custom component similar to React components, but I've encountered an issue with placeholder replacement using {{ }}. Despite finding a workaround for the error I faced after days of struggling, I still lack a full understanding of the problem. It seems that when returned from within a class constructor, I cannot use methods like [...].join("") or access elements in an array using [...][1] without them being interpreted as [object Object]

Code snippet & Issue Description

To prevent interference with nested components, I opted for a Depth-First Search (DFS) through child nodes of my component and delegated the parsing task to a subclass. The specific condition causing trouble was:

      if (current && current?.getAttribute) {
          current.innerHTML = new _Fo_Component_PlaceholderParser({ node: current, content: current.innerHTML })
      }

In the _Fo_Component_PlaceholderParser class:


class _Fo_Component_PlaceholderParser {

    constructor({ node, content }) {
         this.node = node;

         return this.placeholderParser(content);
    }

     placeholderParser(value) {
        if(value.trim === "") {
            return value
        }
        
        const parts = value.split(/(<\/?\w+[^>]*>)/g);

        const stack = [];
        let output = [];

        for (let part of parts) {
            const trimmedPart = part.trim();

            if (/^<\w+[^>]*>$/.test(trimmedPart)) {
                stack.push(trimmedPart);
                const processedTag =
                    stack.length === 1
                        ? trimmedPart.replace(/\{\{.*?\}\}/g, "testing")
                        : trimmedPart;

                output.push(String(processedTag));

                if (this.isSelfClosing(trimmedPart)) {
                    stack.pop();
                }
            } else if (/^<\/\w+>$/.test(trimmedPart)) {
                stack.pop();
                output.push(String(trimmedPart));
            } else if (/\{\{.*?\}\}/.test(trimmedPart) && stack.length === 0) {
                output.push(String(trimmedPart.replace(/\{\{.*?\}\}/g, "testing")));
            } else if (trimmedPart.length > 0) {
                output.push(String(trimmedPart));
            }
        }

        return output.join("");
    }

//rest of the method ...
}

The issue arises in the _Fo_Component_PlaceholderParser where the class directly returns this.placeholderParser(), which in turn returns output.join("").

However, when displayed on the DOM, output.join("") shows as [object Object] even though it contains the parsed data when logged during the process.

Interestingly, returning just output displays perfectly as an array in the DOM, comma-separated.

Hence, using output.join("") shouldn't be problematic, right?
Moreover, it's not just the .join method.
Even trying output[0] results in [object Object], making manual string concatenation of output futile as it simply displays

[object Object] [object Object] [object Object]...
.

Surprisingly, removing my logic and replacing output with ["test", "it works"] leads to the same outcome. The values were hardcoded and directly returned, yet the behavior remained consistent. Why?

What is the underlying issue here?

The only successful approach so far has been returning output directly from the class and then performing the joining operation within the DFS condition as:

if (current && current?.getAttribute) {
    current.innerHTML = new _Fo_Component_PlaceholderParser({ node: current, content: current.innerHTML }).join("")
}

Seeking Assistance With

  1. Why does output.join("") return [object Object] on the DOM when returned from the class?
  2. Could this be related to how JavaScript handles return values from a class constructor?
  3. What would be the correct way to resolve this perplexing issue?

Answer №1

One challenge that arises is that new SomeClass always returns an Object, regardless of the constructor output. This can lead to confusion as the returned object may be another Object instead of an instance of the desired class. For instance, returning a String from the constructor can cause unexpected results.

To address this issue, consider the following:

class _Fo_Component_PlaceholderParser {

    constructor({ node, content }) {
        this.node = node;
        this.content = content;
    }
    toString() {
        return this.placeholderParser(this.content);
    }
    // ... unchanged code here

update: as suggested by gre_gor's comment

class _Fo_Component_PlaceholderParser {

    constructor({ node, content }) {
         this.node = node;

         return new String(this.placeholderParser(content));
    }

This revised approach could provide a more effective solution.

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

problem encountered when transferring data using ajax

I'm struggling with figuring out how to use an ajax function My goal is to send PHP variables via ajax to another page when a user clicks on a link Javascript function sendData(a, b, c, d) { $.ajax({ url: "page.php", typ ...

What is the best way to determine the moving average of an Object value within an array?

In my dataset, I have an array called 'scores' that contains 4 objects. export const scores = [ { day: '1', Barcelona: 1, Real: 3, Valencia: 0}, { day: '2', Barcelona: 4, Real: 6, Valencia: 3}, { day: '3', Bar ...

Mobile website includes a share button that activates share dialogs for iOS and Android systems

Can a share button be created on my website that will trigger share dialogs on iOS and Android devices? Specifically, I am referring to the dialogs shown below for each system: https://i.sstatic.net/dw759.jpg https://i.sstatic.net/NS8W3.png I am lookin ...

Basic HTML and JavaScript shell game concept

After spending several days working on this project, I am struggling to understand why the winning or losing message is not being displayed. The project involves a simple shell game created using HTML, JavaScript, and CSS. I have tried reworking the JavaSc ...

Verifying the presence of a popover

Utilizing bootstrap popover in my project, I am encountering an issue where the target variable may not always exist on the page. Currently, I am displaying the popover using the following code snippet - target = $('#' + currentPopoverId.data(& ...

The object variable is not recognized by the Javascript method

var Geometry = function(shapeType) { this.shapeType = shapeType; addEventListener("resize", this.adjust); } Geometry.prototype.adjust = function() { alert(this.shapeType); } . var figure = new Geometry('rectangle'); After resizin ...

Failed to fetch user id from server using Ajax request

I am facing an issue with my form that includes a text input field and a button. After submitting the form, I extract the value from the user field and send an ajax request to ajax.php to retrieve the userID from the server. The server does return a value, ...

Failure in rendering components with React and ElectronThe issue of rendering components with

As a newbie to the world of React and Electron, I have been experimenting with separating my components into different JSX files and importing them to render in div tags within my index page for an Electron app. However, I'm facing some confusion as i ...

Scripts fail to load randomly due to RequireJs

I have obtained an HTML template from a platform like Themeforest, which came with numerous jQuery plugins and a main.js file where all these plugins are initialized and configured for the template. I am now in the process of developing an AngularJS applic ...

What are the benefits of using Bower.js when npm is already functioning well?

When working in the main project directory, running the command npm init will create a file called "package.json". If I need to install dependencies such as angular, jQuery and bootstrap, I can use the following commands: npm install angular --save-de ...

Cordova plugin for Ionic has not been defined

I am facing a challenge in my Ionic app. The issue arises when the cordova.js file containing a crucial plugin does not initialize until after the controllers.js script has been downloaded and executed. As a result, attempts to use the plugin in the contro ...

Challenges arising with the express search feature

Currently, I am in the process of developing an API for a to-do application. I have successfully implemented the four basic functions required, but I am facing some challenges with integrating a search function. Initially, the search function worked as exp ...

Exploring the functionality of a multidimensional array

This particular program utilizes a multidimensional array with three sizes. The first size represents the rows, the second represents the columns, but what exactly does the third size indicate? Another point to consider is that the array is supposed to b ...

The issue with Angular's mat-icon not displaying SVGs masked is currently being investigated

I have a collection of .svgs that I exported from Sketch (refer to the sample below). These icons are registered in the MatIconRegistry and displayed using the mat-icon component. However, I've observed issues with icons that utilize masks in Sketch ...

Using VueJS to dynamically manipulate URL parameters with v-model

Hello, I am new to coding. I am working on calling an API where I need to adjust parts of the querystring for different results. To explain briefly: <template> <div> <input type="text" v-model="param" /> ...

AngularFire: Retrieve the $value

Having an issue logging the service.title to the console as it keeps returning as a strange object. .factory('service', function($firebase, FBURL, $routeParams) { var ref = new Firebase(FBURL + "services/" + $routeParams.serviceId); var titl ...

What are some tips for creating an improved React list container component?

I have a small application that fetches movie data. The component hierarchy is not very complex. The state is stored in App.js and then passed down to the Movies.js component, which simply displays a list of movies in a ul element. Data passing from App.j ...

The shuffling process in PHP may not always truly randomize the elements within an array

Currently, I am fetching results from my database and storing them in a JSON array. However, the data is being retrieved in a sequential manner based on category, for example, 1, 2, 3, 4. I would like to randomize this array so that the data is fetched in ...

How to save an array to a text file on the server side

After defining my javascript array as var seatsArray = []; with some contents, I'm looking to save the contents of that array to a .txt file on the server upon the user clicking a button. The text file does not exist yet, so it needs to be created. A ...

Transferring data from localStorage to MySQL database

Can anyone suggest a simple method for transferring data from localStorage or sessionStorage to a MySQL database using callbacks? I assume that AJAX would be involved, but I'm struggling to locate a comprehensive tutorial on the process. Essentially, ...