Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can a Javascript function level const variable take on a different value each time the function is called?

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading