javascriptloopsfor-looptemplate-literals

For Loop inside Template Literals?


Is it a way to loop inside Template Literals? Obviously this could be done by mapping an array like this:

array = ["a", "b", "c"]
console.log(`foo ${array.map(i => i).join(" ")} bar`)
///foo a b c bar

But what if we need to loop somthing for specific times? like this:

`foo ${for (let i = 0; i <= 10; i++) {Somthing}} bar`

Solution

  • You can just use an IIFE there:

    `foo ${(function fun() {
      // Do your loop here
      // Return the result as a string
    })()} bar`
    

    I would advise against it and just create the normal function, call it, assign the return value to a variable and use the variable inside template literal placeholder.