Storing Template Literals in JavaScript Arrays: A Quick Guide

I have encountered an issue with storing text in an array for easy retrieval using a value. I want to use template literals within the strings so that they can change based on user input (for example, displaying their name). I have successfully implemented this when including the string directly in the function, as shown below:

textbox.textContent =  `what does ${nameTemp} do?`;

This code works perfectly and updates the displayed text according to the user input. However, the following code does not work as expected. It always displays "tim" as the name (default value for "nameTemp"):

textbox.textContent2 = Title[1];

In the provided code snippet, you can see that the first line within the saveName() function, which includes the full string with the template literal, performs correctly. However, the second line, where the string is retrieved from the array, does not update accordingly. Instead, it continues to display 'tim'. What am I missing here? How can I effectively store strings in an array with variable elements? Any suggestions would be greatly appreciated.

var nameTemp = `tim`;

let Title = [];
Title[0] = "What are you called?";
Title[1] = `what does ${nameTemp} do?`;

const input = document.createElement('input');
input.type = "text";
input.id ="nameText";
input.className +='inputStyle';

function addNameInput()
{
    container.appendChild(input);
}

function saveName()
{
    if (nameText.value !== null)
    {
        nameTemp = nameText.value;
        textbox.textContent =  `what does ${nameTemp} do?`; //This works, it displays the inputted name
        textbox.textContent2 = Title[1];  // This will always display 'tim'
        nameText.parentNode.removeChild(nameText);
        incrementState();
    }
}

Answer №1

Template strings in Javascript are evaluated upon creation and do not automatically update. The Title[1] is set to "tim" initially, and even if you change the nameTemp variable, it will remain unchanged. If you wish to store template strings in an array, you can store a function that returns a template string like this:

Title[1] = () => `What does ${nameTemp} do?`;

Then, to retrieve the value, you can use:

textbox.textContent2 = Title[1]();

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

Arranging a Multidimensional Array Based on Array Values

Currently, I am in the process of developing a message system for a project I am working on. My main objective is to organize an array of conversations based on the datetime of the latest message. Below is a snippet of the array: Array( [0] = Array ( ...

Tips for ensuring the middle row remains sandwiched between the header and footer rows in Bootstrap

After adding styles for img with max-height:100% and max-width:100%, the display looked fine with just images. However, upon further inspection, I noticed that if the middle row (which can contain one or two columns side by side) has multiple images or an ...

Having trouble with adding text to circles in D3 on a line?

I have successfully created some line charts on d3 and then added circles to every 3rd element of the line. Now I am attempting to add text to those circles as well. // defining a circle variable var circles=g2 .append("g") .attr("i ...

Recording and preserving an array (AS3)

In my code, I have an array where responses to questions are recorded using a list response. A loop iterates through the questions in the array, and once the last question is reached, a "continue" button becomes visible for the user to click and proceed. I ...

Encountering incorrect JSON formatting even though the content is accurate

I'm encountering an error while trying to fetch the JSON. It seems to be in the wrong format. Below is the JSON data: { "favorite_page_response": "<div class=\"col-md-12 col-lg-12\">\n <div class=\"cart\ ...

Reloading Vue router view following a successful AJAX request

Currently, I am working with a Vue Router set up that consists of two components: a list view and a detailed view. The challenge I am facing is when the data is fetched via ajax, the non-router list updates successfully but the router view does not reflect ...

Encountering a problem while attempting to create a React application using Vite

I attempted to create a React app using the following command npm create vite@latest filemanager However, when I tried to run the app using npm run I encountered the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

Implementing click binding on elements generated post applyBindings operation

After calling applyBindings, I have an element that is dynamically created. <span data-bind="html: $root.someObservable() && $root.generateLink()" /> The someObservable observable is set to true after applyBindings is called. The generateLi ...

Navigating through scroll bars in Reactjs

Currently, I am working on developing a React application, and I want to incorporate a full-screen title page as one of its key features. The challenge I am facing is related to the scrolling behavior on the title page. My goal is to have the page automati ...

Trouble accessing data property within a method in Vue 3 with Typescript

I am facing an issue with accessing my data in a method I have written. I am getting a Typescript error TS2339 which states that the property does not exist in the type. TS2339: Property 'players' does not exist on type '{ onAddPlayers(): vo ...

Which nodejs versions are compatible with async Iterators?

Which iterations of nodejs are compatible with async Iterators? Can it be adapted to function on previous versions of nodejs? usage for await (let content of promises) { // promises => array of promise objects console.log(content); } ...

Unable to submit value on Ajax-powered dynamic select form

I need help with a dynamic Select element inside a form that is not submitting its value. Here is the code snippet: <table> <form> <tr> <td><select>(options values)</select></td> <td id='fill'>< ...

Utilizing the $primary SCSS variable within Angular Material 2

Currently, I am utilizing angular-cli and following the theming guide to develop a personalized theme for an angular/material2 application. Within the scss file, the primary and accent colors are linked to the $primary and $accent scss variables respectiv ...

Embedding Array into Mongodb is an efficient way to store and

Whenever I attempt to store array data within MongoDB using the query below, it always shows a success message without actually storing any data in an empty array inside MongoDB. My goal is to successfully store array data inside MongoDB as shown in the f ...

The Node.js timestamp is later than the current date of the client

When storing data in MongoDB with the recording date, I utilize new Date() in Node.js and return that date with an AJAX response. To calculate the elapsed time from when the data was stored in MongoDB, I create a new date on the client-side. Then, I determ ...

Adjust the increment of the CSS class property

Just a quick query! I'm attempting to adjust the css width property through JavaScript in this manner: document.getElementById("progressvalue").style.width = "80%"; .progress { width: 100%; max-width: 500px; border: 3px solid black; height: ...

Experiencing challenges with the functionality of the submit button

Every time I try to save the content from the second textarea field by clicking 'submit', it ends up saving the content from the first textarea instead. I am struggling to understand how to properly connect the buttons to their respective textare ...

Issue encountered while appending new rows to the tbody of a table

I'm encountering an issue with the append function within a for loop in my code. The string being passed to the function isn't parsing correctly and results in an error. How can I go about resolving this problem? Thanks! function getDetailPopUp ...

Dynamically insert a new row into an HTML table using AJAX and refresh the table with .load method

I am facing an issue with my HTML table that loads data dynamically through a PHP snippet containing SQL queries. There is a Select option and a button on the table to add a new row, which triggers an AJAX procedure to send the data to PHP for insertion in ...

What is the best way to extract data from multiple instances of <span> tags and store them in an array?

I am in search of the most effective method for extracting multiple span tags from various spans and organizing them into an array or JSON object for future use. (I'm unsure whether an array or JSON is the optimal choice.) HTML: <span class="car" ...