Why Const? Declare a Read-Only Variable with the const Keyword

Tell us what’s happening:
Hi. I’ve got a question to ask while going through this exercise.
In the lesson, it says that const variable cannot be reassigned once it’s assigned with a value.
Then why is the function printManyTimes does not throw an error when it’s called with another value?
Isn’t the value of const SENTENCE reassigned everytime the function is called with different values?
Thanks.

Your code so far


function printManyTimes(str) {
  "use strict";

  // change code below this line

  const SENTENCE = str + " is cool!";
  for(let i = 0; i < str.length; i+=2) {
    console.log(SENTENCE);
  }

  // change code above this line

}
printManyTimes("freeCodeCamp");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword

The variable SENTENCE only exists within the scope of the function. Function executes, goes out of scope. Gets called, new scope.

Here are some videos for your viewing pleasure


1 Like

You function was called once, therefore your const variable was assigned once.
Even if you called the same function twice, it wouldn’t matter because the variable is within a different scope.

However, if you so something like this…

const help = "helping";
help = "not helping";  //This line won't get executed.

it won’t work.