Mutate function declared with constant

Under topic ES6: Mutate an Array Declared with const, it says

it is important to understand that objects (including arrays and functions) assigned to a variable using const are still mutable.

Can you please provide example of const function mutation ?

const myObj = { foo: 1 }
myObj.foo = 2;

const prevents reassignment: it’s still the same object, with the same reference.

Arrays and functions are also types of objects. You could add properties to a function, in practice this is not going to be done very often.

EDIT: sorry, should have provided this - here’s a usecase for adding properties to functions. You can add static properties to classes, and the function equivalent of doing that, in the context of React code:

React class component:

class SomeComponent extends Component {
  static navigationOptions = ({ navigation }) => {
    // some config for nav buttons
  }

  render() {
    return (
      // component JSX here
    );
  }
}

React function component:

const SomeComponent = () => (
      // component JSX here
    );

SomeComponent.navigationOptions = ({ navigation }) => {
    // some config for nav buttons
  };

I didn’t understand this. I could successfully assign 2 to the property foo. How does const play any role here ?

const myObj = { foo: 1}
const myObj = { bar: 1}
// Error, there is already something
// assigned to `myObj`

But

myObj.foo = 2;
// This is fine, it's still the same object

myObj is referring to the container, not the values inside the container.

Thanks a ton for quick clarification.

Regards,
Vikram

1 Like