I'm new in code in general, I'm learning javascript, some days ago I make a "Path Checker", just for look what Can I do with my current knowledge, now 1 week later I'm try to improve it, less code, more reusable functions, but I don't know why Don't run correctly, the logic it's good alone, but with the variables dont' work.
This is the basic logic.
let moto1='';
function checkMoto1() {
if (myMotosInTheGarage === 0 && moto1 === '') {
openAlert(displaySorryAlert); //global function that works
} else if (myMotosInTheGarage === 0 && moto1 === 'out') {
moto1 = 'return'; //change status
myMotosInTheGarage++; //sum to a count
countMotos; //const of write the myMotosInTheGarage in a textContent
changeBackground(btn1, 'red'//global function that works
} else if (myMotosInTheGarage >= 0) {
if (moto1 === '') {
moto1 = 'out';
myMotosInTheGarage--;
countMotos;
changeBackground(btn1, 'green');
} else if (moto1 === 'out') {
moto1 = 'return';
myMotosInTheGarage++;
countMotos;
changeBackground(btn1, 'red');
}
}
}
And I try this to a global function.
let moto1='';
function checkMoto1() {
checkMotoGarage(moto1, btn1);
};
function checkMotoGarage(motonumber, btnnumber) {
if (myMotosInTheGarage === 0 && motonumber === '') {
openAlert(displaySorryAlert);
} else if (myMotosInTheGarage === 0 && motonumber === 'out') {
motonumber = 'return';
myMotosInTheGarage++;
countMotos;
changeBackground(btnnumber, 'red');
console.log(`the ${btnnumber} it's ${motonumber}`);
} else if (myMotosInTheGarage >= 0) {
if (motonumber === '') {
motonumber = 'out';
myMotosInTheGarage--;
countMotos;
changeBackground(btnnumber, 'green');
console.log(`the ${btnnumber} it's ${motonumber}`);
} else if (motonumber === 'out') {
motonumber = 'return';
myMotosInTheGarage++;
countMotos;
changeBackground(btnnumber, 'red');
console.log(`the ${btnnumber} it's ${motonumber}`);
}
}
};
The moto status don't change in the global function, Why is that? What I did wrong?.
Nowhere in the updated version of the code does this variable ever change:
In the original working version the code updates that variable:
But in the new version you're only updating the local variable in that function, not the global variable:
If you want to maintain and update a global variable, you'll need to update that:
Alternatively you can return the value from the function (just remember to do everything else you need to do before returning) and assign/use the value wherever you call the function. But the function is already modifying other global variables so you may as well remain consistent with the patterns you're using.