What causes the literal loop to produce additional commas in its output?

Having some trouble understanding template literals in javascript, particularly the syntax. Whenever I run this loop, it seems to output extra commas between each iteration:

character = () => {
    const traits = ["Knowledge", "Agility","Strength", "Charisma", "Perception", "Magical power"];
    return `${traits.map(() => '')}`
};

Here's the full code snippet:

            character = () => {
                const dice = rndAssign(6, 16),
                traits = ["Knowledge", "Agility","Strength", "Charisma", "Perception", "Magical power"];
            return `<table>
                    <thead>
                        <tr>
                            <td>&nbsp;</td><td>D6</td><td>Mod</td>
                        </tr>
                    </thead>
                    <tbody>
                        ${traits.map(elm => trait(elm))}
                    </tbody>
                </table>`
            };

Answer №1

When the map function only returns an empty string, it results in printing commas for the empty array. If you return a value instead, it will print the actual values.

character = () => { const traits = ["Knowledge", "Mobility", "Strength", "Charisma", "Perception", "Magic Power"]; return ${traits.map(() => '')} };

() => {
    const traits = ["Knowledge", "Mobility", "Strength", "Charisma", "Perception", "Magic Power"];
    return `${traits.map(() => '')}`
}


character()
",,,,,"


character = () => {
    const traits = ["Knowledge", "Mobility", "Strength", "Charisma", "Perception", "Magic Power"];
    return `${traits.map((v) => v)}`
};


() => {
    const traits = ["Knowledge", "Mobility", "Strength", "Charisma", "Perception", "Magic Power"];
    return `${traits.map((v) => v)}`
}


character()


"Knowledge,Mobility,Strength,Charisma,Perception,Magic Power"

Answer №2

I'm not quite sure what your exact goal is here. Why use loops and literals when you can simply convert the array to a string using the join method?

createCharacter = () => {
    const traits = ["Knowledge", "Agility","Strength", "Charisma", "Perception", "Magical Power"];
    console.log(traits.join(' '))
};

createCharacter();

Answer №3

It is the default behavior of the `toString` method for arrays. To create a string without commas, you can use the `join` method on the array.

const table = () => {
  const traits = ["Knowledge", "Agility", "Strength", "Charisma", "Perception", "Magic power"];
  return `
    <table>
      <thead><tr><th>Foo</th></tr></thead>
      <tbody>${traits.map((e) => `<tr><td>${e}</td></tr>`).join(' ')}</tbody>
    </table>
    `
};

document.body.innerHTML = table()
table,
th,
td {
  padding: 5px;
  border: 1px solid black;
}

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

javascriptEmbed youtube video thumbnail dynamically as users input a URL

I am currently working on a React frontend for my web app. One of the features I want to implement is a URL input box, with an image display panel below it. The goal is that when a user enters a YouTube URL into the input box, the thumbnail of the correspo ...

How to dismiss a jQueryMobile dialog without triggering a page refresh

I've encountered a question similar to this before, but there wasn't any solution provided. The issue I'm facing is that I have a form and when a user clicks on a checkbox, I want to open a popup/dialog for them to enter some data. However, ...

Repeating single records multiple times in AngularJS with ng-repeat

I've been working on a project using AngularJS and have encountered some strange behavior with ng-repeat. My controller is returning data to ng-repeat as follows: ..... //Other JS Functions ..... var app = angular.module('main', ['ngTa ...

What is the proper way to update a dropdown value in a React JS component?

Can you please guide me on how to assign a value in a dropdown in react js? I am retrieving the dropdown data after a delay of 3000 milliseconds and then I need to set a value in the dropdown. const App = ({ children }) => { const val = "ax"; const ...

What is the process for transforming JSON into a different format?

Currently, I have a JSON array structured as follows: var data = { report: [ { Name: "Nitin", comment: [ { count: 0, mName: "Feb" }, ...

Guide on loading numerous JavaScript files into a database using the mongo shell

I am faced with the task of loading multiple js files that contain collections creations and seeds into my database using the mongo command. Currently, I have been manually loading data from each file one by one like so: mongo <host>:<port>/< ...

When it comes to successful payments, should you use `checkout.session.async_payment_succeeded` or `checkout.session.completed` in the Stripe event?

I'm feeling a little uncertain about the differences between two events: checkout.session.async_payment_succeeded & checkout.session.completed Currently, I am utilizing checkout.session.completed, but I'm wondering if checkout.session.async ...

What steps should be taken to address the issue when the .media$thumbnail.url cannot be located

Creating a custom widget for bloggers <script type="text/javascript"> function mycallback(jsonData) { for (var i = 0; i < jsonData.feed.entry.length; i++) { for (var j = 0; j < jsonData.feed.entry[i].link.length; j++) { ...

Tips for using Jquery to round up currency values

Is there a way to round up various currencies using jQuery? I have a specific requirement: 10.30 → 10 //Round down if below .5 10.60 → 11 //Round up if after .5 849.95 → 850 1,022.20 → 1022 ...

Conditionally enable or disable button by comparing textbox values within a gridview using C# programming

Hey there! I'm currently diving into the world of JavaScript and C#. Feel free to correct me if you see any mistakes along the way. Check out my gridview code snippet below: <asp:GridView ID="GridView1" CssClass="table table-hover table-bordered" ...

Fill your HTML form effortlessly using data from Google Sheets

I am relatively new to this topic, but I'm seeking a solution to populate an Apps Script Web App HTML dropdown form with names directly from a Google Spreadsheet. At the moment, I've managed to retrieve an array of names from column A in my sprea ...

Assign a value to a TextInput component when pressed

The Component I created is as follows: class TextInputComp extends Component { constructor(props){ super(); this.state = { thetext: '' } } submitText = (text) => { Alert.alert("Text Submitted!", text); } render() { ...

Which names can be used for HTML form tags in jQuery?

Recently, I encountered an issue related to jQuery form serialization which stemmed from naming a form tag "elements". The problem arose when using jQuery $(’form’).serialize(). Here is an example of the problematic code: <form> <input name=" ...

Utilizing the Fetch API to append JSON data to the document in Javascript

I am working on sending JSON data back to my express app using fetch and a POST method. Here is the code snippet I have: fetch('https://development.c9users.io/canadmin',{ method:'POST', body:JSON.string ...

Turn off Closure Compiler formatting guidelines

I've inherited an old codebase that's been minified using Closure Compiler. As part of our efforts to modernize and optimize the code, we've set up a CI job to highlight any warnings or errors. However, some of these warnings are irrelevant ...

The browser unexpectedly cancelled the ajax call triggered by the beforeUnload event

Seeking advice on a web application that needs to save user input data through an ajax call when they leave the site. Currently using "Fetch" in a beforeunload event listener, but encountering issues with browsers cancelling the ajax call (specifically th ...

inserting information into HTML document

I've noticed that this particular method hasn't been addressed yet due to the document.GetElementsByClassName I'm using, but for some reason it's not working. My goal is to add a specific value (a string) to the page. I have located an ...

obtain the final result once the for loop has finished executing in Node.js and JavaScript

There is a function that returns an array of strings. async GetAllPermissonsByRoles(id) { let model: string[] = []; try { id.forEach(async (role) => { let permission = await RolePermissionModel.find({ roleId: role._id }) ...

Activate the button click event using JavaScript or jQuery automatically when the page is loaded in Internet Explorer

Currently, I'm faced with this code snippet: window.onload = function () { $('#btnFilter').click(function (e) { btnFilter(e); }); } The issue here is that the function only works when the button is clicked. What I actually ...

The object function router(req, res, next) is encountering an error as it does not contain the required method for handling the request

I am trying to add a new row to my MySQL database, but I encountered an error message. Here is the scenario: I have set up Passport and hjs in my project. I am passing form data from app.js to a JavaScript file where I aim to insert the data. Object funct ...