I’m trying to find out if my use of ‘const’ is appropriate given the behavior I am seeing.
function showInstructions() {
const againText = (clickCounter > 0) ? "again " : "";
my2DContext.fillText("Click " + againText + "to try to do the thing", myCanvas.clientWidth / 2, myCanvas.clientHeight / 2);
}
The first time this function is called, clickCounter is 0, and it displays:
"Click to try to do the thing"
called later, when clickCounter > 0, the function displays:
"Click again to try to do the thing"
This works as intended.
Is this an appropriate use of ‘const’? Should this be the expected behavior? Does it match other languages?
>Solution :
Can a Javascript function level const variable take on a different value each time the function is called?
Yes, as your example shows.
Is this an appropriate use of ‘const’?
Yes. However it would be more appropriate if clickCounter was declared as a parameter of the function.
Should this be the expected behavior?
Yes, it’s the same as var, let or function: a declaration inside a function is creating a new variable in the scope and of that function on every call.
Does it match other languages?
Yes. Few languages have variables that when declared inside a function are shared between multiple calls to the function.