5/7 Why use const?


#1

Inside the toggleMood method, a variable is set to a ternary operator:

const newMood = this.state.mood == 'good' ? 'bad' : 'good';

But I thought this variable cannot be changed or re-declared, so when it toggles moods, how does this work? Why not use var? Just wondering!

Thanks.


#2

A const cannot be updated or removed, that is correct. But if the object is a data structure (Object, Array) that object can be updated.

const my_obj = {};
const my_array = [];

The type cannot be changed or reassigned, but the objects themselves are completely mutable.

As we can see above, state is an object, not a value.


#3

Yes we cannot change the data type that has been assigned to the const

my_obj = {}

but we are allowed to update the contents of the object

my_obj = {age: 25}

or even

my_obj.name = "tommy";

console.log(my_obj);
//{age: 25, name: "tommy"}

also here is video on the topic https://youtu.be/sjyJBL5fkp8
@ 11:58 it discusses const


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.