Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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`
like image 864
Behnam Avatar asked Feb 11 '20 13:02

Behnam


3 Answers

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.

like image 149
Roberto Zvjerković Avatar answered Nov 20 '22 16:11

Roberto Zvjerković


You can use reducer to achieve in ES6

const anArray = [
  {
    "name": "pulha",
    "as": "puli"
  },
  {
    "name": "puli",
    "as": "moka"
  },
    {
    "name": "moka",
    "as": "starbucks"
  },
  {
    "name": "starbucks",
    "as": "sweet"
  },
    {
    "name": "sweet",
    "as": "krispey"
  },
  {
    "name": "krispey",
    "as": "free"
  }
];

$('#an-example-showing-template').append(`
  ${anArray.reduce((updated, latest) => updated.concat(`<li>${latest.name} alias ${latest.as}</li>`), '')}
`)
#an-example-showing-template > li {
  list-style-type: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="an-example-showing-template"></ul>
like image 4
Amarnath Reddy Dornala Avatar answered Nov 20 '22 14:11

Amarnath Reddy Dornala


It would be better to implement your function outside the backtick expression like this:

function helloworld() {

let string;

for(let i = 0; i <10 ; i++){
string = 'Hello World!'    
} 
   return string
}

//Inside the backtick

`${helloworld()}`
like image 1
ImLuctor Avatar answered Nov 20 '22 14:11

ImLuctor