07. Immutable and Mutable Values in Javascript
We all know that there is a concept with immutable and mutable values in javascript. But what does it mean? How do we encounter it in programming and what are the points that we should remember when working with them? Those are the questions that will be answered in this tutorial in deep.
What is immutability
Immutable data is a concept which is used in languages widely, which means not changing the original declared value when modifying the reference value.
Example:
let str = "this is a string"; str = str.replace('this', 'hello');
When the strings are mutable values and references should link like following
But when strings are immutable it behaves like this
Strings are immutable in Javascript. Let’s see what are the other values which are immutable and mutable in Javascript.
Immutable values in Javascript
The following are considered immutable in Javascript, which we term as primitive values/literals.
- Reserved keywords
- Booleans
- Numbers
- Strings
Reserved keywords such as undefined
, null
cannot be modified and it makes no sense to modify them as well.
So as Numbers and Booleans. Booleans have only two values true and false which cannot be modified. And for numbers rather than modifying assigning a new value is quite optimistic.
When it comes to strings it can be a bit tricky to understand how they are immutable. As in example 1, the strings are immutable. The following examples will give you more understanding of immutable strings.
let str = "Hello"; let anotherStr = str.toUpperCase(); console.log(str); // Hello console.log(anotherStr); // HELLO let subStr = str.substring(0, 2); console.log(str); // Hello console.log(subStr); // He
This means the value represented by str
is not changed and it cannot be changed in the javascript.
let str = "Hello"; let he = 'He'; let subStr = str.substring(0, 2); // He console.log(he === subStr); // true
This is mapped in memory like the following. (Not the exact way but in high level)
This way of string sharing is known as String Interning and javascript does it by sharing strings to optimize memory.
Mutable values in Javascript
Mainly objects and arrays are known as mutable values in javascript. This means the original value will be modified when you do a change.
const value = {a: 'a', b: 'b'}; value.a = 'c'; console.log(value); // {a: 'c', b: 'a'};
Same with the arrays.
const array = ['1', '2', '3']; array[0] = 1; console.log(array); // [1, '2', '3'];
Objects are not compared with the value, they are rather compared with the reference to the value.
For Example:
const user1 = { age: 24 }; const user2 = { age: 24 }; const arr1 = []; const arr2 = []; console.log(user1 === user2); // false console.log(user1 == user2); // false console.log(arr1 === arr2); // false console.log(arr1 == arr2); // false
Because of this behavior, objects and values are known as Reference Types.
Reference types are compared if the declared reference points to the same value when comparing.
const user1 = { age: 24 }; const user2 = user1; user1.age = 32; console.log(user2.age); // 32 console.log(user1 === user2); // true
Equality of reference values or objects and arrays
Since the objects are mutable, it is not straight forward to check the equality of them. For that we need to check each attribute and see whether the objects are equal. This leads to other issues like comparing the prototype of the object correctly.
A deep comparison to find the equal object can be found here: https://github.com/ReactiveSets/toubkal/blob/master/lib/util/value_equals.js
You can shallowly compare an object easily with the following.
For example:
const shallowCompare = (obj1, obj2) => { const obj1Keys = Object.keys(obj1); const obj2Keys = Object.keys(obj2); return obj1Keys.length === obj2Keys.length && obj1Keys.every(key => obj1[key] === obj2[key]); } shallowCompare({}, {}); // true shallowCompare({}, {b: 'c'}); // false shallowCompare({a:'a'}, {b: 'c'}); // false shallowCompare({a:'a'}, {a: 'a'}); // true
For a quick and easy solution, you can use lodash
isEqual
function if you are using the library in your codebase. But it will add an overhead of library size to your bundle.
Copy or clone objects and arrays
To copy an array you will have to copy the elements from one to another.
Array shallow copy example:
const a = ['a', 'b', 'c']; const b = a; const c = [...a]; const d = a.slice();
Object shallow copy example:
const obj = {x: 1, y: 2, z: 'Hello'}; // using spread operator const clone1 = {...obj}; // using Object assign const clone2 = Object.assign({}, obj); // using JSON parse and stringify, this will deep copy but has issues // not a good solution to use const clone3 = JSON.parse(JSON.stringify(obj)); // proposed native clone method // should be available in latest browsers and nodejs 11 onwards // may not work in older versions of browsers const clone4 = structuredClone(obj);
If you need to clone in a more robust way you can use lodash
clone
and cloneDeep
methods. This will add an overhead to the library size.
51 COMMENTS
Thank you, I’ve just been looking for information about this topic for ages and yours is the greatest I have found out so far. However, what about the bottom line? Are you positive about the supply?
This could raise the body s levels of everolimus what does lasix do to blood pressure
Your writing style is engaging and relatable, making it feel like a conversation with a friend rather than reading an article.
Great article! I really enjoyed reading it and appreciate the insights you shared.
Your article is a valuable resource for anyone interested in this topic. I’ve already shared it with several friends and colleagues.
Your article is an excellent resource for anyone looking to learn more about this topic. The information is presented in a clear and concise way.
I appreciate the depth and breadth of knowledge you bring to this topic. Your articles are always informative and insightful.
Your honest and relatable writing style is impressive. You’re not afraid to share your personal experiences and vulnerability with your readers.
I like the way you present your argument in a very clear and structured way.
Your article is a great starting point for anyone looking to explore this topic further. Thank you for providing such a comprehensive overview.
Your valuable and detailed views are impressive, and I am amazed by the amount of research you have put into this article.
Your writing is so relatable and empathetic. It’s clear you have a deep understanding of the emotions and experiences your readers may be going through.
Furrer et al viagra prank porn SSNRIs and SSRIs were subsumed as a group the two SSNRIs venlafaxine and duloxetine both had similar rates of HN, whereas a class effect has been described for SSRIs Egger et al
Your passion for this subject shines through in your writing. It’s evident that you deeply care about this issue and want to make a difference.
This is a well-written article. Your writing style is engaging and easy to follow.
In addition, I had a wonderful time with that. In spite of the fact that both the narration and the images are of a very high level, you realise that you are anxiously expecting what will happen next. Regardless of whether you choose to defend this stroll or not, it will be essentially the same every time.
How To Create Website Audit report for free ? watch this https://www.youtube.com/watch?v=CxzaJOyFnQc
What i do not understood is in truth how you are not actually a lot more smartlyliked than you may be now You are very intelligent You realize therefore significantly in the case of this topic produced me individually imagine it from numerous numerous angles Its like men and women dont seem to be fascinated until it is one thing to do with Woman gaga Your own stuffs nice All the time care for it up
I loved as much as youll receive carried out right here The sketch is tasteful your authored material stylish nonetheless you command get bought an nervousness over that you wish be delivering the following unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike
I do not even know how I ended up here but I thought this post was great I dont know who you are but definitely youre going to a famous blogger if you arent already Cheers
This was beautiful Admin. Thank you for your reflections.
Wow wonderful blog layout How long have you been blogging for you make blogging look easy The overall look of your site is great as well as the content
I agree with the practical and useful advice you provide in this article.
Thank you for the informative and helpful article! I appreciate how you presented the information clearly and concisely.
What topics would you like to see covered in future posts? Let us know in the comments.
I luckily came across this awesome website earlier this week with great content for fans. The site owner knows how to captivate visitors. I’m so pleased and hope they keep up their fine work.
greate post i like very much..
men thats great very good..
I was suggested this web site by my cousin Im not sure whether this post is written by him as no one else know such detailed about my trouble You are incredible Thanks
Your perspective on this topic is spot-on, and I couldn’t agree more. It’s time we make a change and take action.
Good post! We will be linking to this particularly great post on our site. Keep up the great writing
I appreciate you sharing this blog post. Thanks Again. Cool.
Your passion for this subject shines through in your writing. It’s evident that you deeply care about this issue and want to make a difference.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
I like the way you present information in an easy to understand language.
Your article addresses an important issue that needs to be discussed more. Thank you for bringing attention to it.
Your article is well-organized and easy to read. I appreciate the effort you put into it.
Your article is a great resource for anyone looking to educate themselves on this issue. Thank you for sharing your knowledge.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
I do believe all the ideas youve presented for your post They are really convincing and will certainly work Nonetheless the posts are too short for novices May just you please lengthen them a little from subsequent time Thanks for the post
What’s up Dear, are you actually visiting this web page
regularly, if so after that you will without
doubt take fastidious knowledge.
Fantastic beat I would like to apprentice while you amend your web site how could i subscribe for a blog site The account helped me a acceptable deal I had been a little bit acquainted of this your broadcast offered bright clear concept
My brother suggested I might like this website He was totally right This post actually made my day You cannt imagine just how much time I had spent for this information Thanks
Somebody essentially lend a hand to make significantly articles Id state That is the very first time I frequented your website page and up to now I surprised with the research you made to make this actual submit amazing Wonderful task
Eu simplesmente não consegui sair do seu site antes de sugerir que realmente gostei das informações padrão que uma pessoa fornece aos seus visitantes. Estarei novamente de forma constante para verificar novas postagens
Your article helped me a lot, is there any more related content? Thanks!
Site fantástico Muitas informações úteis aqui, estou enviando para alguns amigos e também compartilhando deliciosas E, claro, obrigado pelo seu suor
obviamente gosto do seu site, mas você precisa testar a ortografia em algumas de suas postagens. Vários deles estão repletos de problemas ortográficos e acho muito difícil informar a realidade, por outro lado, certamente voltarei novamente
I share your level of appreciation for the work you’ve produced. The sketch you’ve displayed is elegant, and the content you’ve authored is sophisticated. Yet, you appear to be concerned about the possibility of heading in a direction that could be seen as dubious. I agree that you’ll be able to resolve this matter efficiently.
Techarp This is my first time pay a quick visit at here and i am really happy to read everthing at one place
Your article helped me a lot, is there any more related content? Thanks! https://www.binance.com/ru/register?ref=V3MG69RO