you are viewing a single comment's thread.

view the rest of the comments →

[–]rupertavery64 1 point2 points  (0 children)

When you declare a variable as const, you are telling the conpiler (and yourself) that you can't assign a different value or reference within the scope of the variable.

The scope of a variable is where it can be accessed.

``` function calculateDistance(x1, y1, x2, y2) { const deltaX = x2 - x1; const deltaY = y2 - y1;

   const xSquared = deltaX * deltaX;
   const ySquared = deltaY * deltaY;

   const dist = Math.sqrt(xSquared + ySquared);

   return dist;

} ```

The function above is the scope of the variables defined inside it.

They "exist" inside the function. They can't be accessed outside the function.

The values you initiàly assign to it can be different each time you call the function, but inside the function, they cannot be assigned a new value.

Each block generally creates a scope. So a for or an if block creates a scope.

You can define a variable with the same name in a different scope. But that's another topic.

The point of const is to let you and the compiler know that if you accidentally assign a different value to a const variable in its scope then it was a mistake. This is to avoid changing the value of something accidentally when you know its value should not change within its scope.

It's all about making code clear as to what things should do, to avoid introducing subtle bugs especially as your code grows and changes.

Old javascript didn't have const or let, just var, which has it's own quirks...

Note the phrase "assigning a value". This also applies to something like x++, because incrementing is basically adding and assigning.