I come from c# background where immutable is achieved with public get ,private set properties. I have read that numbers in javascript are immutable so how can I do the following
var x = 6 / 2;
console.log(x); // 3
x = 8;
console.log(x); // 8
I have changed x, which I thought I couldn't?
The numbers themselves are immutable. The references to them that are stored in the variable are not.
So 6 / 2
gets you a reference to the immutable 3
, and then = 8
assigns a new reference to the immutable 8
.
C# also allows a programmer to create an object that cannot be modified after construction (immutable objects). If you assign a new object in C# to an immutable object, like say a string. You are getting a new string rather than modifying the original.
What you demonstrated here isn't all that different. You can try a const
instead
const x = 6 / 2;
console.log(x); // 3
x = 8;
console.log(x); // 3
Reference
Syntax
const varname1 = value1 [, varname2 = value2 [, varname3 = value3 [, ... [, varnameN = valueN]]]];
Browser compatibility
The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8). As of Safari 5.1.7 and Opera 12.00, if you define a variable with const in these browsers, you can still change its value later. It is not supported in Internet Explorer 6-9, or in the preview of Internet Explorer 10. The const keyword currently declares the constant in the function scope (like variables declared with var).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With