when I enter at the prompt 0, than I am expecting an alert "stop" but receive "go" instead. Can you help me to get the alert "stop"?
var toyota = {
make: "Toyota",
model: "Corolla",
fuel: 0,
tank: function(addingfuel) {
this.fuel = this.fuel + addingfuel;
},
start: function() {
if (this.fuel === 0) {
alert("stop");
} else {
alert("go");
}
},
};
var addingfuel = prompt("Please enter fuel added", "liter");
toyota.tank();
toyota.start();
4 Answers 4
It will work fine if you change this code
this.fuel = this.fuel + addingfuel;
to
this.fuel = this.fuel + (addingfuel || 0);
Comments
You need to change your code a little bit
var toyota = {
make: "Toyota",
model: "Corolla",
fuel: 0,
tank: function(addingfuel) {
this.fuel = this.fuel + (addingfuel || 0);
},
start: function() {
if (this.fuel === 0) {
alert("stop");
} else {
alert("go");
}
},
};
Explanation When you pass nothing while calling toyota.tank() this will take argument as undefined and append undefined with a number will give you NaN
0 + undefined
Comments
window. prompt returns string type as a return value. That is why when you adding fuel (number) to addingfuel (string) it results "00" and your condition fails.
In order to overcome this issue, you should cast string to number before working with that value.
tank: function(addingfuel) {
var numberValue = parseFloat(addingfuel, 10);
numberValue = isNaN(numberValue) ? 0 : numberValue
this.fuel = this.fuel + numberValue;
}
2 Comments
You've to pass the addingfuel with your tank(addingfuel) function other wise addingfuel contains undefined so finally it will show the go instead of stop.
N.B the value of addingfuel is string so you've to cast it to integer like this parseInt(addingfuel) otherwise your this.fuel === 0 condition will fail
Let try this way,
var toyota = {
make: "Toyota",
model: "Corolla",
fuel: 0,
tank: function(addingfuel) {
this.fuel = this.fuel + parseInt(addingfuel);
},
start: function() {
if (this.fuel === 0) {
alert("stop");
} else {
alert("go");
}
},
};
var addingfuel = prompt("Please enter fuel added", "liter");
toyota.tank(addingfuel); // you need to pass this otherwise it is undefined
toyota.start();
+addingfuel;2. pass ittoyota.tank(+addingfuel);