3 ms·
const doesn't actually stop data from changing, just reassignment. const user = {id: 1, status: 'active'}; user.status = 'disabled'; is valid javascript
by wnevets 7y ago
const doesn't actually stop data from changing, just reassignment.
const user = {id: 1, status: 'active'};
user.status = 'disabled';
is valid javascript
- echelon 7y agoWhich is to say that the const pointer itself doesn't change. It doesn't impose any constraints on the values of any underlying data structures. Javascript could use some proper immutable types.
- mywittyname 7y agoYou're talking about two different things. In this case, you'd use... const user = Object.freeze({id: 1, status: 'active'}); But const is immaterial to this topic, as it only prevents you from being able to reassign user to some other value, i.e., user = 7; While... let user = Object.freeze({id: 1, status: 'active'}); user.status = 'disabled'; // throws an error. Provides the behavior that you're seeking to guard against, regardless of let/var/const usage.
- wnevets 7y ago>You're talking about two different things. In this case, you'd use... No, I'm talking about the behavior of const.
- Jach 7y agoI've wondered why the JS people didn't call their keyword for this purpose "final" like Java did.
- ollran 7y agoThat is how object oriented languages work. It is a constant reference to a mutable object. final int[] arr = {1, 2, 3}; arr[1] = 10; is valid Java.