Why is the number unchanged in Javascript?

I read the question and answer here:

javascript numbers are immutable

But for me it’s not clear enough why the number (primitive type) is immutable? Just because they create a new link but don’t overwrite the value?

If a new link is created on each assignment

var x = 5;
x = 1;

Will we have a 100x new link in the next cycle?

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

Is it effective? I think I do not see properly.

+4
source share
5 answers

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

Will we have a 100x new link in the next cycle?

- . . . x R1.

x++ , , 1. , :

R1: 5

, , ADD R1 1,

R1: 6

.. . .


? , .

, .

, , , , .

Mutability " ", " ".

Mutability , , , , .

, , . , . JavaScript, :

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

, value-type ( JavaScript), , . :

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

, , a.add(1) a (.. a = a + 1).

+3

, : 5 - 5, .

- :

let x = 5;

5 x, 5. x:

x = 4;

5: , , , x.

while 0, 1, 2, ... x: x++ x.

, Javascript:


EDIT: , Javascript , ( Number). , , x, becauseno: . Felix Kling .

+1

- , ( ) . "" . .

. , .

, , . . , .

0

,

var a=12;
a=45;

;

1. 12 . () . 2.than, 45 . () . , 12, .

0

:

JavaScript boolean, undefined, null, number, symbol, string . , . , : ( ) , , , , . .

, , - . , , , , .

:

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.js

Libraries, such as immutable.js, provide types that combine the properties of primitive types and objects: Types from immutable.js behave like regular objects if you do not modify them. When you change the property of an immutable object, a new object is created, and the change is visible only through this new object. The advantage is that you save space in memory, and you can quickly check the equality of objects by simply comparing their references. You get a set of types that behave like integers, but you can store more complex structures in them.

-1
source

Source: https://habr.com/ru/post/1686299/


All Articles