I’m trying to increment a number in a Template Literal in JS, but instead of incrementing the number, it’s printing it. Here’s the code:
Code:
function outputFAQResults(results) {
if(results.faqs) {
const gridClass = results.faqs.length > 1 ? "grid-2" : "grid-1";
let count = 1 // Here's the number I want to increment in a map loop
return `
<div data-result-type="faqs" class="accordion">
<h2 class="grid-item-heading gold-line">FAQ's</h2>
<div class="search-results-section">
<ul class="${gridClass} found-results list-reset">${results.faqs.map((item) => `
<li class="search-result search-result--faq" tabindex="0">
<div class="search-result__question"><button data-toggle="collapse" data-target="#faq-${count}" aria-expanded="false" aria-controls="faq-${count}">${item.question}</button></div>
<div id="faq-${count}" class="search-result__answer collapse">${item.answer}</div>
</li>`${count++}).join("")}
</ul>
</div>
</div>`} else {
return "";
}
}
As you can see, for every map, I’m trying to increase the count
variable by one so I can use a Bootstrap Collapse. How can I use the variable without printing it?
2
Answers
If you want to increment the variable but not output it, don’t put it inside the template literal. Change the
to
However, as mentioned in the comments, there is no reason to have your own counter and increment it. Use the index that is passed as the second argument to your
map
callback:variable++
postfix unary operator result is the previous value of the operand which is definitely is printed by${}
template interpolation. Use++variable
, which returns incremented value, on the FIRST occurrence of a variable in a template: