0

I know in JS the primitive values are immutable values and objects are mutable, but, what does it exactly mean?

For example:

var foo = 1;

then we have

foo = 2;

did foo mutate?

Is that applicable for every language? or does everyone applies it under its own rules?

Jamo
  • 494
  • 5
  • 24
  • 4
    The notion of mutability applies to *values*, not variables. – Pointy Oct 02 '17 at 18:18
  • 2
    Sounds like a duplicate of your [previous question](https://stackoverflow.com/q/46392335/1048572) – Bergi Oct 02 '17 at 18:24
  • @Pointy True, but we could apply the notion of immutability to scopes and get constants. – Bergi Oct 02 '17 at 18:25
  • 1
    Different languages have different types that are immutable. In C you can modify strings (they're really just arrays), unless they're declared `const`. Few languages allow you to modify numbers, though. – Barmar Oct 02 '17 at 18:27
  • @Bergi...yeah, it is very similar. I did not give it the approach that I wanted for the first time. Thanks! – Jamo Oct 02 '17 at 18:27
  • 1
    @Jamo in some languages (Erlang), variables are also immutable: once you assign a value to a variable in Erlang, the variable cannot be assigned a new value. JavaScript variables are not like that unless they're declared with `const`. – Pointy Oct 02 '17 at 18:49
  • @Pointy Thanks! that is good to know! – Jamo Oct 05 '17 at 17:26

2 Answers2

2

As said by @Pointy, when you speak about immutability and mutability, you speak about values and not variables.

In JavaScript, strings and numbers are immutable by design. Maybe those example can help you understand https://www.sitepoint.com/immutability-javascript/

DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
sheplu
  • 2,937
  • 3
  • 24
  • 21
0

An Immutable Object is one whose state cannot be changed after it is created. It applies to values, If you want variables to be immutable they would have to be declared constant

var str = 'hello world';

str[0] = '1';

// value remains unchanged
console.log(str);

const x = 1;
// err cannot change value
x = 2;
console.log(x);
marvel308
  • 10,288
  • 1
  • 21
  • 32