6

I have read the question and answer here:

javascript numbers- immutable

But it's not enough clear for me why the number (primitive type) are immutable? Just because they create a new reference but not overwrite the value?

If on each assignemt is created a new reference

var x = 5;
x = 1;

Would we have 100 times a new reference in the following loop?

while (x < 101)
{
    x++;
}

Is that efficient? I think I am not seeing correctly.

Jamo
  • 494
  • 5
  • 24
  • 5
    What would it mean if the number 5 were mutable? – Pointy Sep 24 '17 at 16:35
  • Reading the answer in the question you linked: The numbers themselves are immutable (or you could say constants). The variable x is a reference to a number/constant. It also says there that it is the same in all programming languages. Otherwise you could remove/overwrite numbers and mess up the whole math/calculations that the language can do. Right? – Krisztián Balla Sep 24 '17 at 16:40
  • Mmm but if the number are somewhat constants why we can reassgin them values? x= 5 then x=1. – Jamo Sep 24 '17 at 16:46
  • 3
    You can't. `x` is a variable, `5` and `1` are numbers. Numbers are immutable, variables declared with keywords that allow reassignment (in current JS, `var` and `let`) are not. As for "is it efficient?": yes. Processors understand numbers at the hardware level. And your code has the same reference `x` to a different number at each iteration. – Mike 'Pomax' Kamermans Sep 24 '17 at 16:59
  • _"Would we have 100 times a new reference in the following loop?"_ That would be the expected result, yes? – guest271314 Sep 24 '17 at 17:01
  • I wanted to answer your question, but I'm actually not sure what exactly it is that you want to know. Are you asking why numbers are *considered* to be immutable or are you asking why someone made the decision to make them immutable in JavaScript? – Felix Kling Sep 24 '17 at 18:53
  • 2
    there are no references to primitive numbers. those numbers are stored as variable value always in the same place in memory. – Marcin Malinowski Sep 24 '17 at 21:13

5 Answers5

3

I'm honestly not quite sure what kind of answer you expect since I don't quite understand what you are confused about. But here we go:

Would we have 100 times a new reference in the following loop?

Variables are just containers for values. At a low level a variable is basically just a label for a memory address or a register. E.g. variable x might point to register R1.

x++ would simply increment the number that is stored in that register by 1. Lets assume our register looked like this:

R1: 5

After incrementing it, which can be a single operation, such as ADD R1 1, we would get

R1: 6

I.e. we simple overwrote the previous value with a new one. And we do that multiple times.


Is that efficient? I think I am not seeing correctly.

Incrementing a number by one is as simple of an operation as it can get.

Sure, you could implement mutable numbers on a higher level, but it certainly wouldn't make things more efficient or simpler.

Mutability doesn't make much sense for "single value" values, because mutating such a value basically means replacing it with a different value "in place".

Mutability makes more sense for values that are composed of other values such as lists and dictionaries, where one part changes and the other stays the same.

Additionally, mutability only seems relevant when a language has reference type data types. With that I mean that multiple variables can hold a reference to the very same value of a data type. Objects are reference-type in JavaScript, which allows you to do this:

var a = {foo: 42};
var b = a;
b.foo = 21;
console.log(a);

If data types are not of a reference-type, called value-type, (which primitive values are in JavaScript), then mutability doesn't matter because it would be indistinguishable from immutability. Consider the following hypothetical scenario with a mutable, value-type number:

var a = MutableNumber(42);
var b = a; // creates a copy of MutableNumber(42) because it's a value type
a.add(1);
console.log(a, b); // would log 43, 42

In this scenario it is not possible for two variables to refer to the same mutable number value, a.add(1) is indistinguishable from assigning a new value to a (i.e. a = a + 1).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • So, can we say that numbers are immutable because each variable (containers) has a different reference? The number cannot be modified by reference. – Jamo Sep 26 '17 at 21:27
1

I could understand your question , the thing is , inside the while loop , everytime the x will point to the new value , whereas the old value will be made ready for garbage collection , so the memory is mantained still.

Read this for better understanding : https://developer.mozilla.org/en-US/docs/Glossary/Mutable

So about the mutablity , your understanding is correct , the variable references the new value , the old value isn't changed , hence primitive values are immutable.

Refer: https://developer.mozilla.org/en-US/docs/Glossary/Primitive

CHECoder08
  • 41
  • 3
0

Mutation is a change of state while numbers (the primitive type) are pure state objects. Any mutation to such a "object" state is actually a new number. Number itself is like an identifier of a mutation of bits in a cell of computer memory.

Therefore numbers are not mutable. Same as colors or characters.

It is also worth claryfining that a new number will ocupy the same memory cell as the old one for any given variable. Actually replacing the old one. Therefore there is no performance hit of any kind.

  • What do you mean with "pure state objects"? – Jamo Sep 26 '17 at 19:50
  • If one would try to describe a primitive value as an object that object would not have any methods and the object itself when used in expression would evaluate to its state as single value. – Marcin Malinowski Sep 26 '17 at 20:01
0

i dont understand entirely this,

var a=12;
a=45;

we can infer from ;

1.firstly interpreter allocate a chunk of memory and locate 12 to this area. actually (a) is label of this memory area. 2.than, interpreter allocate a new memory cell and locate 45 to this area. lastly (a) is associated with this new memory cell. The memory cell that contain 12 is destroyed by garbage collector.

-1

Primitive values vs. references:

In JavaScript values of type boolean, undefined, null, number, symbol, string are primitive. When you assign them to a variable or pass them as an argument to a function, they always get copied. In contrast objects have two parts to them: Object (it's data) is stored in one chunk of memory and what you assign to a variable is a reference pointing to that object. Object itself is not copied on assignment.

Because numbers are always copied when you assign them to a variable it is impossible to change a number and see that change through some other variable without actually assigning a new value to that variable. In contrast when you change a field on an object, all variables pointing to that object will see that change.

Let's see some examples:

var a = 1;
var b = a; //This creates a new copy of value 1
console.log(a, b); // 1 1
a = 2;
console.log(a, b); // 2 1


var obj_a = {attr: 1};
var obj_b = obj_a; //This makes a new reference to the same object.
console.log(obj_a, obj_b); // {'attr': 1} {'attr': 1}
obj_b.attr = 2;
console.log(obj_a, obj_b); // {'attr': 2} {'attr': 2}

Immutable objects: immutable.js

Libraries like immutable.js provide types that combine properties of primitive types and objects: Types from immutable.js behave as ordinary objects as long as you don't change them. When you change a property of an immutable object, a new object is created and the change is only visible through that new object. The benefit is that you save space in memory and you can quickly check equality of objects by just comparing their references. You get a set of types that behave like integers but you can store more complex structures in them.

Matjaž Drolc
  • 356
  • 4
  • 9
  • 1
    Pass by reference and using references for objects is **not** the same thing. JavaScript is pass by value, and in case of objects the value is a reference. You are confusing how **values** are represented with how variables and parameters are evaluated. Those are two different things. – Felix Kling Sep 24 '17 at 17:09
  • it is not true to say that strings are always passed by value and therefore copied. Strings are acutally always passed by a reference. – Marcin Malinowski Sep 24 '17 at 17:10
  • @MarcinMalinowski: see my previous comment. JavaScript is pass by value, that value may be a reference. The nice thing about immutable values is that they may be copied or they may be referenced. The implementation can do whatever it wants. – Felix Kling Sep 24 '17 at 17:13
  • Read your first sentece in the your response. – Marcin Malinowski Sep 24 '17 at 17:15
  • To be clear, this is what pass by refence means: `var bar = 42; function foo(baz) { baz = 21; }; foo(bar);`. After calling foo, bar would have the value 21, because baz references the same memory location as bar. But this is not how it works in JavaScript, no matter the value of the variable. https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – Felix Kling Sep 24 '17 at 17:17
  • You are confusing variables and values. In your example value is copied while in case of parameters in js those are already created new. Passing parameters by reference is possible in c++ – Marcin Malinowski Sep 24 '17 at 17:30
  • @MarcinMalinowski: was this comment for me? I don't confuse variables and values. But others who post here do. And of course other languages have pass by reference semantics, I'm only talking about javascript. – Felix Kling Sep 24 '17 at 17:32
  • Thank you for the comments. I removed incorrect use of passing by value/reference semantics. Is the following statement accurate? Strings behave for all purposes as if they were primitive data type. However because strings can be quite long it would be wasteful to always copy them. A reference to a string is stored in variables but unlike objects strings can only be modified through use of one of it's methods which always make a separate changed string and return a new reference. This makes them similar to Immutable.js data types. – Matjaž Drolc Sep 25 '17 at 04:41