2

I am new to react and have a question about immutability in es6 to help my understanding of immutability.

For example, I know this is invalid in JSX as it is reassigning a const.

const helloWorld = 'Hello World';
helloWorld = 'Bye World';

however, this seems valid:

const helloWorld = {greeting: 'hello World'};
helloWorld.greeting = 'bye world';

In essence, the concept i'm trying to wrap my brain around is the idea that while although helloWorld is immutable, the value it holds is not. How and why does this still represent immutability? And why would you use it in this fashion instead of using a let variable?

Thanks and apologies for the noob question if it is as such! :)

user1337902
  • 236
  • 3
  • 11
  • 3
    This is nothing to do with react and jsx. Read basic javascript first before diving into frameworks. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const – artin Apr 02 '17 at 16:30

1 Answers1

2

First const is not a part of JSX, it's language feature in ECMAScript6. const only make the variable a constant and the value it refers is still mutable.

If you want to make the value immutable, use Object.freeze or a library like Immutable.js.

Tharaka Wijebandara
  • 7,955
  • 1
  • 28
  • 49
  • indeed, i'm aware of this being the way it works. my question is more to the _why_. – user1337902 Apr 02 '17 at 16:38
  • Simply `const` doesn't represent immutability. If you have seen using `const` inside react components that because those variables are not meant to change and it has nothing do with immutability. – Tharaka Wijebandara Apr 02 '17 at 16:56