1

I am bit confused, Wikipedia (I know, I know) defines immutability as

immutable object is an object whose state cannot be modified after it is created.

while the JS implementation example states

In JavaScript, some built-in types (numbers, strings) are immutable

I understand now that in JS both Numbers and Strings are Objects but why would they be considered immutable when I can clearly change the value of any Number or String variable?

daniel.sedlacek
  • 8,129
  • 9
  • 46
  • 77
  • 9
    You "change" by creating a *new* string or number, not by *modifying* the original – Alex K. Apr 21 '15 at 14:14
  • 3
    You are talking about assigning different values to variables. – thefourtheye Apr 21 '15 at 14:14
  • `var x = 42` assigns an immutable number/value 42 to your variable. if you do `x++`; then the 42 is destroyed and replaced with a new immutable number: 43. – Marc B Apr 21 '15 at 14:15
  • You can't change the value of e.g. 8 or 23 or "puppies!". – molbdnilo Apr 21 '15 at 14:16
  • `'foo'[1] = 'a'` - nope. – deceze Apr 21 '15 at 14:17
  • 2
    The string/number is immutable. The variable you're storing it in is not. – JJJ Apr 21 '15 at 14:17
  • Notice that also booleans, `null` and `undefined` are immutable. Though it's most noticable with strings, which could be seen as a composite value. – Bergi Apr 21 '15 at 14:20
  • does that mean that I can change value of property of immutable object? If str1="abc";str1="xyz"; did not mutate the str1 variable then how about obj1.str1="abc";obj1.str1="xyz"? – daniel.sedlacek Apr 21 '15 at 15:57
  • That is no different from assigning values to variables. I don't see how assigning property values has anything to do with mutating strings even if it were possible. – JJJ Apr 21 '15 at 16:40

0 Answers0