Const vs let confusion - need help clarifying

I need help understanding the different use cases for using let vs const when declaring a variable.

Here is the W3 literature:

When to Use JavaScript const?

If you want a general rule: always declare variables with const .

If you think the value of the variable can change, use let .

In this example, price1 , price2 , and total , are variables:

Example

const price1 = 5;
const price2 = 6;
let total = price1 + price2;

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

This is a value that can be changed.

If I understand correctly, the prices are declared with const because the values will not change but the total variable is declared with let because the value will change. Is this correct?

But here is where I am confused. The price of something will change eventually. So you would need to change its value when it does. Maybe the example is whats confusing me but shouldn’t the value of the price variables need to be able to change as well? What is a better example of this const and let use case?

Hello,

Yes, you understand correctly the difference between let and const. In the example (which I also find a little confusing), if one of the prices needs to be changed later, the code will need to be updated to use let and not const anymore.

An example for the usage of const could be:
You have a function that is returning an error message when something goes wrong. The error can happen in multiple places in your code. You will put the message in a const to avoid someone updating it involuntarily.

function myFunction()
{
  const ERROR_MESSAGE = "invalid values";
  
  try {
    let hasError = false; // hasError is *let* as this value can change in this function

    // ... Some code ...

    if (hasError) {
      return hasError;
    }

   // ... More code ...
  } catch (error) {
    return ERROR_MESSAGE;
  }
}

Or another example could be if you want to store a list of values, and those values will not and cannot be changed, you will use a const.
Example: const languages = ['javascript', 'csharp', 'typescript'];

In this case not quite. When it comes tor objects and arrays, you cannot reassign the array/object itself, but you can still freely modify its contents when const is used, for example:
image

Oh, thanks for the info, I didn’t think about that ><

1 Like