Can someone explain to me my error in logic for why this doesn't work to assign a key value pair in javascript and initialize their values to 0? The values return as undefined.
What is the best way to do this instead?
Example:
const letters = ['i','c','l','e'];
let dict = {};
dict = letters.map(value => dict[value] = 0);
CodePudding user response:
map()
returns an array of the results of the callback. So you're replacing the object with that array.
Since you're modifying the object in the loop, you don't need to assign back to the variable. And since you don't need an array of the results, you should use forEach()
rather than map()
letters.forEach(letter => dict[letter] = 0);
BTW, in JavaScript we call these objects, not dictionaries.