Experimenting with code:
let obj ={};
let newItems = ["Apple", "Banana", "Carrot", "Donut"].map(item => {
obj.count= Math.random()*item.length;
obj.itemName= item;
return obj;
});
console.log(newItems);
The output generated is:
(4) [{…}, {…}, {…}, {…}]
0: {count: 1.4648989727265578, itemName: "Donut"}
1: {count: 1.4648989727265578, itemName: "Donut"}
2: {count: 1.4648989727265578, itemName: "Donut"}
3: {count: 1.4648989727265578, itemName: "Donut"}
length: 4
__proto__: Array(0)
This result is not as expected. However, when I modify the code to:
let obj;
let newItems = ["Apple", "Banana", "Carrot", "Donut"].map(item => {
obj = {
count: Math.random()*item.length,
itemName: item
} ;
return obj;
});
console.log(newItems);
The desired output is achieved:
(4) [{…}, {…}, {…}, {…}]
0: {count: 4.2813861024052615, itemName: "Apple"}
1: {count: 5.850654082147917, itemName: "Banana"}
2: {count: 6.646446034466489, itemName: "Carrot"}
3: {count: 1.7062874250924214, itemName: "Donut"}
length: 4
__proto__: Array(0)
Can someone explain why there is a difference in behavior between these two code snippets?