Help get this topic noticed by sharing it on Twitter, Facebook, or email.

Why Use `const` When Declare Mutable Objects

In "Learning JavaScript" by Ethan Brown, I'm curious to know why he insists on using `const` when declaring objects, especially if they are mutable and we usually expect them to change over time? Even in his examples he is changing them after declaring them with `const`! A very minor issue, but irritating my good sense just the same.
1 person has
this question
+1
Reply
  • Hi Pete,

    I passed your message on to the author for clarification and he replied with this note:
    ------
    This is an important distinction that I do cover in Chapter 3 in the
    section "Primitive Types and Objects." The const keyword in JavaScript
    simply means that the *variable* can't be re-assigned: if the variable
    points to a mutable object (i.e., a non-primitive), that object is still
    able to change. If you need an object to be truly immutable (i.e., can't
    be modified), you'll have to use Object.freeze.

    Another way to look at it as this: some object X is still the same object
    even if you change it's properties. Your car is still the same car no
    matter what passengers are in it. The car is const, it's contents are not
    necessarily. Constant primitives, such as numbers, are different. 3 will
    always be 3, and it's a different thing altogether if you change it to 5.
    You could make either argument with strings, but JavaScript considers
    strings to be primitive, and the string "foo" is inherently different than
    the string "foobar", in the same way 3 is different than 5. But objects
    and arrays don't change their identity simply because their content
    changes. I hope this helps you understand my use of const throughout the
    book.
    -------
    I hope that helps.

    Best regards,
    Chris Olson
    O'Reilly Customer Service
  • (some HTML allowed)
    How does this make you feel?
    Add Image
    I'm

    e.g. indifferent, undecided, unconcerned sad, anxious, confused, frustrated kidding, amused, unsure, silly happy, confident, thankful, excited