Most relevant answers here do not refer to let, which is block scoped, but to var, which is hoisted. I can't seem to get a definitive answer to this.
I have a variable declared globally that initializes once:
let firePaused = false;
and then a function in the keyboard handler that is running everytime I press a button:
function actOnKeyPress() {
if (rightPressed) {
game.hero.rotate(game.hero.speed);
} else if (leftPressed) {
game.hero.rotate(-game.hero.speed);
}
if (!firePressed) {
firePaused = false;
}
if (firePressed && options.numberOfBullets > 0) {
if (!firePaused) {
fireBullet();
firePaused = true;
}
}
}
(not relevant to the question, but it's purpose is to only allow the player to fire once, there needs to be a keyup event before they can fire again)
By the rules of clean code I should declare the variable at the top of the function... BUT that means it will be redeclared everytime I press a button.
It says here https://www.sitepoint.com/how-to-declare-variables-javascript/
Initialization: When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.
So I would be creating a whole new variable each time the let keyword is used.
Should I go to the bother of writing a conditional at the start of the function to check if firePaused
is declared yet, and if not declare it? That seems total overkill.