Useful JavaScript Tricks
· One min read
Looping with indices using for
for([i, e] of ["a", "b", "c"].entries()){
console.log(i, e)
}
Also with forEach
["a", "b", "c"].forEach((e, i) => {
console.log(e, i)
})
Creating an array of length n
const n = 10
let ary = [...Array(n)].map((_, i) => i)
// Or alternatively
ary = Array.from({length: n}).map((_, i)=> i)
Sum of an array
let ary = [1, 2, 3, 4, 5]
ary.reduce((_, v) => _ + v)
