JS Concatenation

I'm working with a sample API in JavaScript. My code is the following:
let index = 4;
let api = "https://dummyjson.com/products/${index}";

function fetchData() {
let img = document.getElementById("product-img")
let title = document.getElementById("product-title")
let price = document.getElementById("product-price")
let desc = document.getElementById("product-desc")

fetch(api)
.then(response => response.json())
.then(data => {
console.log(data);
img.src = data.thumbnail;
title.innerHTML = data.title;
price.innerHTML = "$" + data.price;
desc.innerHTML = data.description;
})
}
let index = 4;
let api = "https://dummyjson.com/products/${index}";

function fetchData() {
let img = document.getElementById("product-img")
let title = document.getElementById("product-title")
let price = document.getElementById("product-price")
let desc = document.getElementById("product-desc")

fetch(api)
.then(response => response.json())
.then(data => {
console.log(data);
img.src = data.thumbnail;
title.innerHTML = data.title;
price.innerHTML = "$" + data.price;
desc.innerHTML = data.description;
})
}
Line 2, let api = "https://dummyjson.com/products/${index}"; doesn't work correctly. From my understanding, this is a template literal which acts similarly to concatenation? When I replace this line with: let api = "https://dummyjson.com/products/" + index;, it works correctly. Am I using the ${} incorrectly?
2 Replies
Jochem
Jochem14mo ago
template literals use backticks instead of double quotes the one left of 1 on a QWERTY keyboard so
let api = `https://dummyjson.com/products/${index}`;
let api = `https://dummyjson.com/products/${index}`;
Matt
Matt14mo ago
ahh okay thank you for the clarification I did notice a format change when adding the backticks, previously it looked like an entire string
Want results from more Discord servers?
Add your server