Home > Enterprise >  Can a Javascript function level const variable take on a different value each time the function is c
Can a Javascript function level const variable take on a different value each time the function is c

Time:11-21

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?

CodePudding user response:

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.

CodePudding user response:

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

Short answer: Yes


Long answer

I tried to recreate a quick runnable code base on your example.

  • Every time the click event has triggered the expression in againText variable will be evaluated (ternary operator) and a new value is assigned to the againText variable.

This is normal behaviour, this happens only once the function is called, an error will only occur when you try to reassign a value to the againText within the function.

function showInstructions() {
  let clickCounter = document.getElementById("click").value;
  const againText = Number(clickCounter) > 0 ? "again " : "";
  document.getElementById("text").innerHTML =
    "Click "   againText   "to try to do the thing";
}

document
  .getElementById("btn")
  .addEventListener("click", showInstructions);
<input type="number" id="click" />
<button id="btn">click</button>
<p id="text"></p>

CodePudding user response:

In javascript 'const' can not be reassigned but it is mutable, so yeah i think this an appropriate use of 'const' You can read more about const on MDN docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

  • Related