7

Possible Duplicate:
javascript numbers- immutable

I read Douglas Crockford's book JavaScript: the Good Parts. It says the number in JavaScript is immutable. But numbers in JavaScript is copied by value and we can use operator ++ to change the value. So why say it's immutable? and further, if it's immutable, why numbers are copied by value?

3
  • your answer is here stackoverflow.com/questions/8248568/…
    – Gatekeeper
    May 18, 2012 at 7:25
  • 1
    @Gatekeeper I think they are different May 18, 2012 at 7:39
  • In contrast to other languages, the ++ operator in JavaScript doesn't change the value of a number but creates a new number. Try ` let n = 0; let m = n; console.log(m, n, m === n); ++m; console.log(m, n, m === n); ` Mar 13, 2019 at 9:12

2 Answers 2

6

They are immutable because they are copied by value.

When you do

var x = 4;
x += 1;

you haven't changed the number 4 into the number 5. You have changed the value stored in the variable x from 4 to 5.

2
  • If I changed the value stored in variable x, why say it's immutable. And I think "immutable" means you can't change the memory which variable point to. May 18, 2012 at 7:44
  • And I think += is also an assignment which you bind the variable to another memory if x is immutable May 18, 2012 at 7:48
0

When you modify the members of an object, you modify its contents. The value of the variable (i.e. the reference) stays the same. This is mutable,

When you declare a string, it has a value, but when you change that value a new string is actually created. This means it is immutable.

Similarly with numbers. You can't change a 3 to be a 4. A 3 is always 3, never anything else. So when you assign a variable to another number, you are creating a new number in memory, not assigning the contents of some memory pointed to by some variable to a different value.

4
  • what about ++ operator, it also create a new number in memory? May 18, 2012 at 7:55
  • x++ is identical to x+=1, so yes. May 18, 2012 at 8:22
  • I think it's quite confusing. In python, integer is also immutable and python doesn't provide ++ operator. And I think the reason behind it is that ++ make people think value is changed in-place. And I doesn't understand why JavaScript behave in such an unusual way May 18, 2012 at 10:53
  • Its not just JavaScript that supports ++. Its C#, Java, C, C++ to name a few. It's just shorthand for x = x + 1, however the concept of pre and post increment is also supported (x++ = pre ++x = post). the short of it is, that its a decades old concept, and JavaScript is not behaving in an unusual way. May 18, 2012 at 15:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.