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`
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.
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>
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()}`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With