The use of const and let variables

We learn in the lesson that there is a difference between const en let variables. I guess we use const if we want to make sure nothing in our program can change it?

But what excactly can we do with both variables?
I learned now that if a const variable is a Key:Value pair, we can change the value of a key, even if the variable is const.

So in which ways can we change a const variable and which ways we cant? And how do we use them in software? Do we only use const in cases that we need to make sure we dont change the variable, and all other cases we choose let to be sure?

I believe that const variables cannot have their values reassigned. Someone else can probably give a more indepth answer, though.


I mean you could use let, but for someone reading your code for the first time without much understanding of what the code exactly does, he may not expect a let variable to not change its value :wink: . Using different variable types is a way to make your code more understandable/readable and prevents you from reassigning by accident something you don’t want to be reassigned.

On the topic of the key:value pair. This is something you will touch when learning about objects.

In its essence this has to do with how Javascript works.

Variables in Javascript refer to a chunk of memory. When you assign a variable you create a reference between the variable and a certain value a.k.a. the chunk of memory.

The moment you reassign a variable, you refer to a different piece of memory. You are not changing the chunk of memory itself. You see where I am going here?

When it is a variable of the type const, you can’t change the reference. Meaning it will always refer to the same chunk of memory.

When assigning an object to a variable, you create a reference with set object. You can’t change this reference but you can however modify the chunk’s content/properties (i.e. key: value pair).

Let’s say

const pants = {pantsColor: 'red'};

// This is not allowed. This would reassign 'pants' itself to refer to a different object, i.e. a shirt.
pants = {shirtColor: 'blue'};

// This, however, is allowed.  This would mutate the object 'pants' refers to, but `pants` itself hasn't been reassigned to refer to something else.
pants.pantsColor = 'blue';

Hope this explanation helps :wink:

Happy coding!