Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, Why constant String cannot be modified but constant array can be modified

const name = 1;
name = 2;

When executing this JavaScript I get an error :

TypeError: Assignment to constant variable.
    at Object.<anonymous> (/home/user01/JavaScript/scope.js:2:6)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3

But, on executing below statements, code executes successfully.

const arr = [1,2,3];
arr[1] = 5;

Why are we able to modify an array even if it is declared as constant.

like image 676
rrc1709 Avatar asked Jan 03 '23 01:01

rrc1709


2 Answers

Because the array itself hasn't changed, it is still the same array. In C-like languages an analogue to this would be a constant pointer (to some address in the memory) – you can't change where the pointer points to, but the memory is writable just the same.

In JavaScript, this pointer-like behaviour applies to anything that is not a primitive (i.e. Number, Boolean, String ...), which is basically arrays and objects. If you are wondering why a String is a primitive, it is because in JavaScript Strings are immutable.

like image 154
Aurel Bílý Avatar answered Jan 04 '23 15:01

Aurel Bílý


ES2015 const does not indicate that a value is constant or immutable. A const value can definitely change. The following is perfectly valid ES2015 code that does not throw an exception:

const obj = {};
obj.bar = 42;
console.log(obj.bar);
// → 42

const arr = [1, 2, 3];
arr[1] = 42;
console.log(arr[1]);
// → 42

The only thing that’s immutable here is the binding. const assigns a value ({}) to a variable name (obj) or ([]) to a variable name (arr) , and guarantees that no rebinding will happen. Using an assignment operator or a unary or postfix -- or ++ operator on a const variable throws a TypeError Exception

So, Any of the following lines will throw an exception.

const foo = 27;
foo = 42;
foo *= 42;
foo /= 42;
foo %= 42;
foo += 42;
foo -= 42;

Now question is how to make a variable immutable?

Primitive values, i.e. numbers, strings, booleans, symbols, null, or undefined are always immutable.

var foo = 27;
foo.bar = 42;
console.log(foo.bar);
// → `undefined`

To make an object’s values immutable, use Object.freeze(). It has been around since ES5 and is widely available nowadays.

const foo = Object.freeze({
    'bar': 27
});
foo.bar = 42; // throws a TypeError exception in strict mode;
              // silently fails in sloppy mode
console.log(foo.bar);
// → 2
like image 23
Always Sunny Avatar answered Jan 04 '23 13:01

Always Sunny