最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论
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._pile (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.

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._pile (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.

Share Improve this question edited Aug 19, 2018 at 8:57 raunakchoraria asked Aug 5, 2018 at 15:59 raunakchorariaraunakchoraria 3872 silver badges16 bronze badges 2
  • Because const doesn't mean "immutable", unfortunately. – E_net4 Commented Aug 5, 2018 at 16:00
  • 2 It's because a const can't be reassigned. You are not reassigning the variable when you change an array. If you don't want arr to be mutable you can use Object.freeze(arr) – Mark Commented Aug 5, 2018 at 16:02
Add a ment  | 

2 Answers 2

Reset to default 6

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.

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论