-4

asuming that a "const" is constant, I wouldn't have thought that this is possible:

const obj = { key1: value1, key2: value2 }; obj["key3"] = value3; obj.key4 = value4; 

Can somebody explain it to me?

4
  • 2
    A const "variable" is a variable that cannot be re-assigned to another value once created. By mutating the object the variable still holds the same reference, so the variable did not change. Commented Jun 4, 2021 at 12:29
  • Constant and immutable are two different things. You are expecting obj to be immutable Commented Jun 4, 2021 at 12:34
  • Why was my question voted down 4 times? Does anybody feels so much smarter? Commented Jun 4, 2021 at 12:46
  • 2
    @gear Your question is well formulated with a good example, so that should not be the reason of the downvotes. There is only 1 issue with your example, that is the fact that the variables value1 - value4 are not defined. Changing them to strings resolves this. But the most likely reason for the downvotes is probably the lack of research. If you searched "JavaScript why can I change a const" using any search engine, you would probably find an answer. I personally don't find the question downvote worthy, but I assume others might disagree. Commented Jun 4, 2021 at 14:00

1 Answer 1

4

In your case, you aren't actually changing obj. You're just changing a property of obj, so it isn't considered like you're trying to change a constant.

Only doing this is problematic:

const obj = { key1: value1, key2: value2 }; obj = 5 
Sign up to request clarification or add additional context in comments.

7 Comments

Why would this be downvoted? It's the correct answer.
@Pointy I don't know. 😬
Small addition: if you want to make the actual properties of the Object const, look into Object.freeze: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@divillysausages Oh snap, I didn't know that! That's really cool. Thanks for the addition.
Note that freezing an object is shallow. If the object contains nested objects they are not frozen. eg. obj = { a: 1, b: { c: 2 } } then obj.a = 3 results in an error, but obj.b.c = 3 is still allowed. (only obj is frozen, obj.b is not)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.