Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone a new object simply by assigning object to a variable using Immutable.js

I'm looking at the documentation for Immutable.js, specifically the following:

var map1 = Immutable.Map({a:1, b:2, c:3});
var clone = map1;

but I'm confused as to how simply assigning map1 to clone creates a clone rather than a reference?

Update: The docs state "If an object is immutable, it can be "copied" simply by making another reference to it instead of copying the entire object. Because a reference is much smaller than the object itself, this results in memory savings and a potential boost in execution speed for programs which rely on copies (such as an undo-stack)."

I just tested this in a jsbin though, and clone does === map1. I think their use of the word 'clone' in the docs is a little misleading.

like image 958
ThinkingInBits Avatar asked Dec 13 '15 19:12

ThinkingInBits


People also ask

How do I copy an object from one variable to another in JavaScript?

The Object. assign() function can be used to copy all enumerable own properties from one or more source objects to a target object. This function returns the target object to the newObject variable.

How can we make an object immutable in JavaScript?

To make an object immutable, recursively freeze each property which is of type object (deep freeze). Use the pattern on a case-by-case basis based on your design when you know the object contains no cycles in the reference graph, otherwise an endless loop will be triggered.

Which of the JavaScript function is used to clone the object?

parse() method is used to clone an object.


1 Answers

Since Immutable.Map is immutable, the notion of cloning is obsolete. Their point is that you don't have to bother about cloning or not, it doesn't matter.

The docs are indeed confusing, and indeed it is a reference not a clone. The effect of cloning would be the same anyways.

like image 169
OzieGamma Avatar answered Oct 06 '22 00:10

OzieGamma