I was trying the following code:
let obj ={};
let newIngredients = ["Hello", "Distraction", "Nothing", "Love"].map(el => {
obj.count= Math.random()*el.length;
obj.ingredient= el;
return obj;
});
console.log(newIngredients);
and this is the output I get:
(4) [{…}, {…}, {…}, {…}]
0: {count: 1.4648989727265578, ingredient: "Love"}
1: {count: 1.4648989727265578, ingredient: "Love"}
2: {count: 1.4648989727265578, ingredient: "Love"}
3: {count: 1.4648989727265578, ingredient: "Love"}
length: 4
__proto__: Array(0)
This is not what I wanted. But when I type in the following,
let obj;
let newIngredients = ["Hello", "Distraction", "Nothing", "Love"].map(el => {
obj = {
count: Math.random()*el.length,
ingredient: el
} ;
return obj;
});
console.log(newIngredients);
It returns the following output, which I actually want:
(4) [{…}, {…}, {…}, {…}]
0: {count: 4.2813861024052615, ingredient: "Hello"}
1: {count: 5.850654082147917, ingredient: "Distraction"}
2: {count: 6.646446034466489, ingredient: "Nothing"}
3: {count: 1.7062874250924214, ingredient: "Love"}
length: 4
__proto__: Array(0)
Can anyone please explain why is this difference in behavior between the two code snippets?