I'm grappling with creating a basic program that accomplishes the following:
Develop a function declaration named changePowerTotal which accepts:
- The total current power generated (a numeric value)
- A generator ID (a number)
- The new status of a generator ("on" or "off")
- The amount of power produced by that generator (a number)
Your function must:
- Return the updated total generated power
- Alert the technician using specific formats based on whether the generator is switched on or off.
For turning on, provide an alert as follows:
"Generator #2 is now on, adding 62 MW, for a total of 62 MW!"
And for switching off:
"Generator #2 is now off, removing 62 MW, for a total of 0 MW!"
Here is my current solution:
var generatorId = 2;
var status = "off";
var totalCurrentPower = 62;
var powerProduced = 62;
function changePowerTotal(totalCurrentPower, generatorId, status, powerProduced){
if(status === "off"){
var offPowerTotal = totalCurrentPower - powerProduced;
alert('Generator #' + generatorId + ' is now ' + status + ', removing ' + powerProduced + 'mw, for a total of ' + newPowerTotal + 'MW!');
return offPowerTotal;
}
else {
var onPowerTotal = totalCurrentPower + powerProduced;
alert('Generator #' + generatorId + ' is now ' + status + ', adding ' + powerProduced + 'mw, for a total of ' + newPowerTotal + 'MW!');
return onPowerTotal;
}
}
The issue I'm facing is that the alert isn't triggering, and to make matters worse, as a beginner, there are no errors displaying in the JavaScript console. What could be wrong?
However, when I simplify it by assigning all variables globally and then run an alert, everything works fine (see below). This makes me suspect that the problem lies within the if/else condition in my function.
var generatorId = 2; var status = "off"; var totalCurrentPower = 62; var powerProduced = 62; newPowerTotal = 0;
alert('Generator #' + generatorId + ' is now ' + status + ', removing ' + powerProduced + 'mw, for a total of ' + newPowerTotal + 'MW!');
Any guidance would be highly appreciated. I've also attempted removing the returns and leaving only the alerts, but that didn't resolve the issue.