Night Coder

JavaScript: Better loop instead of for()

Sometimes we only need a quicker way to making a loop with a specific number of loops. Just do this:

[...new Array(10)].forEach((item, index) => {
    console.log(`loop index: ${index}`);
})   

/*
loop index: 0
loop index: 1
loop index: 2
loop index: 3
loop index: 4
loop index: 5
loop index: 6
loop index: 7
loop index: 8
loop index: 9
> undefined 
*/

Using .map() can help a lot:

[... new Array(5)].map((item, index) => {
   return `http://night-coder.com/posts/page-${index+1}`;
})

/*
> Array(5) [
  'http://night-coder.com/posts/page-1',
  'http://night-coder.com/posts/page-2',
  'http://night-coder.com/posts/page-3',
  'http://night-coder.com/posts/page-4',
  'http://night-coder.com/posts/page-5'
]
*/

Leave a Reply

Your email address will not be published. Required fields are marked *