skip to Main Content

Hi I am new to JavaScript and am trying to iterate through a string array and use intrapolation in the output. However it keeps bringing up errors. What am I doing wrong pls?

const beachList = ["sunglasses 🕶", "parasol ⛱", "swimming costume 🩱", "drinks 🍹", "sun cream ☀"];

for (let i = 0; i < beachList.length; i++) {
    const element = beachList[i];
    const intraOutput = 'Pack ${element}';
    console.log(intraOutput);
}

I am expecting:

"Pack sunglasses 🕶"
"Pack parasol ⛱"
"Pack swimming costume 🩱"
"Pack drinks 🍹"
"Pack sun cream ☀"

2

Answers


  1. You need to use back ticks to use string interpolation.

    Change

    'Pack ${element}'
    

    to

    `Pack ${element}`
    
    Login or Signup to reply.
  2. To use Template literals (string interpolation), you need to use backticks.
    Like this:

    const beachList = ["sunglasses 🕶", "parasol ⛱", "swimming costume 🩱", "drinks 🍹", "sun cream ☀"];
    
    for (let i = 0; i < beachList.length; i++) {
        const element = beachList[i];
        const intraOutput = `Pack ${element}`;
        console.log(intraOutput);
    }

    See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals?retiredLocale=de

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search