I’m trying to create a function which simply toggles between 1 and 0, something like…
function rotate () {
//how do I get the # of times the function is run?
if(x %2 ==0){
document.getElementById('rotate') = 0;
} else {
document.getElementById('rotate') = 0;
}
We want a function that can remember things. Usually an IIFE (immediately invoked function expression) is used for that, so that the outer function remembers things, and the returned code is what accesses the information.
When the function is run, isn’r lastValue set to 0? Then isn’t 1-0 (or 1) always going to be the result? The only reason I used the % is cause I wanted to switch around the width and height attributes of
It is overwritten. The line lastValue = 1 - lastValue; overwrites it.
When it comes to const and let, const cannot be reassigned, and let can be reassigned. Let is similar to var, but var has function scope, whereas let has block scope.
To avoid confusion I try to stick to let and const, so that I’m not mixing function scope and block scope. That’s a confusion best avoided.
Most of the variable assignments that I use are const. I only use let on the deliberate occasions when I intend for that value to be changed.
Better is to adjust the function to be called alternate and return true or false, then use that in the condition to decide things.
const alternate = (function iife() {
let lastValue = false;
return function () {
lastValue = !lastValue;
return lastValue;
};
}());
if (alternate()) {
// do asset stuff here
} else {
// do other asset stuff here
}