1

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.

3 Answers 3

1

Check in your code instead of:

'<h1>${item.name}</h1>'

Should be:

`<h1>${item.name}</h1>`

Here is the documentation for Template literals (Template strings)

Demo:

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

const display = Animals.map(({ name }) => `<h1>${name}</h1>`)

console.log(display)

Sign up to request clarification or add additional context in comments.

Comments

0

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);
});

Comments

0
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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.