Mutable and Immutable
Dita Larasati
Posted on June 26, 2022
Honestly, this article is my old personal note as I was in programming bootcamp. Why do I end up to bring this to you? My colleague said that .forEach()
will mutate the array but .map()
won't. Hm. It is true but it is not so true..
In JavaScript, there are primitive and non-primitive value. As MDN said, primitive value is data that is not an object and has no methods or properties such as string, number, bigint, boolean, undefined, symbol, and null.
Thus, the rest will be categorized as non-primitive (Objects). For example, Object literal, Array, Set, Map, Function, and even Class & Instance because it could has a method/property.
Let us see to the example code below:
What actually happened to the primitives are the original value can not be altered. The original value still exist in memory and can be accessed as long as its variable not be assigned to another value.
The opposite thing happens to objects literal, array, and function. With those data types, the variable will refer to the same address where the original value at. That's why it is named Referenced-type Objects.
So, please be careful with referenced-type objects because you could not access the original value once the its variable has been passed into another variable and then computed.
The conclusion is:
Primitives are passing their value but non-primitives are passing their value's address.
In addition, referenced-type objects are always mutable even tho they are declared as const
.
Important thing to remember, variable declaration, const
and let
merely are about re-assign-ability the variable name. Presumably, a keyword to help programmer to be consistent and attentive during development.
Many people I know tends to use let
if they would like to change the element of array or property of object in the next line. But I never do that because that's not how the let
aimed for. You just change the inside or the part of the value, not the entire value.
For the last!
About .forEach()
and .map()
as I was mentioned above
The .forEach()
and .map()
methods have different purpose. .forEach()
is void method, it is just do the looping. .map()
is non-void method, it creates a new array from which the elements got from the result iteration of the calling array.
Posted on June 26, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.