'Having issue with getting value from object variable. No errors showing

I created an array called animals containing two objects. I want to get a value from the name variable in the object animals and insert that value in a return statement in the map method. I used ${} to access the variable.

const Animals = [{
    name: "Lion",
    type: "Carnivore",
  },
  {
    name: "Cow",
    type: "Herbivore",
  },
];


window.addEventListener("DOMContentLoaded", function() {
  let display = Animals.map(function(item) {
    return '<h1>${item.name}</h1>';
  });
  console.log(display);
});

Now I'm supposed to get in the console an array of two items containing the values of the variables -- the result should look like this ['<h1>Lion</h1>', '<h1>Cow</h1>']. But instead I get this ['<h1>${item.name}</h1>', '<h1>${item.name}</h1>']. As you can clearly see, for some reason the ${} was unable to access the variable and get the value. I don't know why this's happening. Console log shows no errors. Plz help me resolve this issue. Thanks in advance.



Solution 1:[1]

Variables inside ${...} structures are template/string literals syntax but in order for them to work they need to be enclosed with backticks instead of single/double quotes.

const animals=[{name:"Lion",type:"Carnivore"},{name:"Cow",type:"Herbivore"}];

window.addEventListener("DOMContentLoaded", function() {
  const display = animals.map(function(item) {
    return `<h1>${item.name}</h1>`;
  });
  console.log(display);
});

Solution 2:[2]

const Animals = [{
    name: "Lion",
    type: "Carnivore",
  },
  {
    name: "Cow",
    type: "Herbivore",
  },
];


window.addEventListener("DOMContentLoaded", function() {
  let display = Animals.map(function(item) {
   return '<h1>'+item.name+'</h1>';
  // return `<h1>${item.name}</h1>`;
  });
  console.log(display);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andy
Solution 2 Madasamy M