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?

Community
  • 1
  • 1
Xiaotian Pei
  • 3,210
  • 21
  • 40

2 Answers2

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.

Greg B
  • 14,597
  • 18
  • 87
  • 141
  • 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. – Xiaotian Pei May 18 '12 at 07:44
  • And I think += is also an assignment which you bind the variable to another memory if x is immutable – Xiaotian Pei May 18 '12 at 07: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.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • what about ++ operator, it also create a new number in memory? – Xiaotian Pei May 18 '12 at 07:55
  • x++ is identical to x+=1, so yes. – James Wiseman May 18 '12 at 08: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 – Xiaotian Pei May 18 '12 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. – James Wiseman May 18 '12 at 15:06