Search code examples
javascriptvariablesvarlet

How to get let inside a block when adding iterations to it?


Imagine:

const arr = ['a','b','c'];
let num;
const incr = arr.map((el, i) => { 
 num += el; 
}
// num is undefined in incr

How to get num inside incr function so it can increment itself on each loop?

Trying to put num inside incr will not result in proper increments as it will be overwritten on each loop.

Shall I use var instead?


Solution

  • You aren't initializing num, so its value is undefined.

    const arr = ['a','b','c'];
    let num = '';
    arr.forEach((el, i) => { 
     num += el; 
    });
    

    This will get you 'abc' in num.

    However, the idiom of accumulating values is better served by .reduce:

    const arr = ['a','b','c'];
    const num = arr.reduce((acc, i) => acc + i);
    

    and better yet, what you're doing here, i.e. joining an array to form a string, is served by .join:

    const arr = ['a','b','c'];
    const num = arr.join('');