Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript numbers- immutable

Tags:

javascript

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?

like image 292
Noel Avatar asked Nov 23 '11 20:11

Noel


2 Answers

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.

like image 146
Quentin Avatar answered Oct 02 '22 01:10

Quentin


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).

like image 35
P.Brian.Mackey Avatar answered Oct 02 '22 02:10

P.Brian.Mackey