.map() function in JS used on a CONST variable
How can listItems be a const? The array elements are appended as we loop through ? Can someone explain what is happening here please.
4 Replies
products.map() returns one item: a new array. That array is the const.
Though const only means that you can’t re-define it. Non-primitive values like objects, maps, and arrays can still be mutated because the const isn’t being redefined it’s being added to.
Another thing to keep in mind is that the value is evaluated first before it is assigned to the variable. So even if you froze the array (preventing mutation) it’s still a const because the return value of the map is what’s being assigned.yep I see
I think, my miss conception was mainly immutability and const, I think these are 2 different concepts?
Yeah, sadly they're 2 different things. Immutability means it can't be change.
const means the value referred to can't be changed.
const PI = 3.14159 is both immutable and constant, since numbers can't be changed. But const PI = { value: 3.14159 } isn't immutable since the object pointed to can be changed.
All primitive data types are immutable: null, undefined, Booleans, numbers, BigInts, strings, and symbols. All Object types are mutable: Objects, Arrays/Array-likes, Weak/Maps, Weak/Sets.
The Object.freeze() static method can make an object immutable. But it only freezes the top-level object. If there are any nested objects you have to freeze them individually. Though this only works on objects and arrays, but not maps/sets.Yep I see, thanks !