0

Consider the following JavaScript code:

const myObject = {
   innerValue: 'test'
}

myObject.innerValue = 'I can still change this, this is not a constant';

If I run this code, the browser outputs no errors, I presume, because only the outer object myObject is a constant and its properties are not. But how valid is this JavaScript code? I mean, are there any negative drawbacks to writing something like this?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Adam Baranyai
  • 3,635
  • 3
  • 29
  • 68
  • 3
    There is no problem writing like it since Javascript is a dynamic language. – micronyks Jul 09 '20 at 17:43
  • 1
    Perhaps you should read https://stackoverflow.com/questions/21237105/const-in-javascript-when-to-use-it-and-is-it-necessary – Wyck Jul 09 '20 at 17:51
  • No, there is nothing wrong with this. It's exactly as intended. You haven't changed the value of `myObject`. – Brad Jul 09 '20 at 17:52

1 Answers1

3

Looks like you already understand that the variable myObject is const, but the object to which it refers is not. That's very much by design for JavaScript. Using const the way you did does not protect you from modifying the object.

You could use a property to protect the value of innerValue.

const myObject = {};
Object.defineProperty(myObject, 'innerValue', {
  value: 'test',
  writable: false
});

console.log(myObject.innerValue);
myObject.innerValue = 'this is not an error but will not change the value';
console.log(myObject.innerValue);
Wyck
  • 10,311
  • 6
  • 39
  • 60
  • 1
    `writable` defaults to `false` so there's no need to set it explicitly. You should mention in your answer that property defined by using `Object.defineProperty()` function is, by default, not enumerable, not configurable and not writable. – Yousaf Jul 09 '20 at 17:53