Reputation: 504
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?
Upvotes: 0
Views: 46
Reputation: 2975
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/
Upvotes: 2
Reputation: 10458
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);
Upvotes: 0