Reputation: 17
I'm writing a pretty simple conditional that is only giving me the "else" answer.
The idea is that if I have more pets (pets) than my friend (friendsPets), then I need to assign it to a new variable (mostPets) to see who has the most pets. But when I log the new variable (mostPets) it's only giving me the answer from the "else" part of the conditional. The new variable should be logging 4 in the console, but it's only logging 0. If I rearrange the conditional statements it does give me 4 - but I know that's not right. I know this is a fairly simple problem, but I'm pretty new to this. Any advice?
let pets = 2;
let friendsPets = 0;
pets = 4;
if (pets > friendsPets) {
let mostPets = pets
} else(friendsPets > pets)
let mostPets = friendsPets
console.log(mostPets);
Upvotes: 0
Views: 99
Reputation: 1800
First, you need to declare your variable mostPets before doing the conditions, otherwise the variable won't be able to be accessed outside of that condition.
Also, your condition else-if was written incorrectly. With those changes it should work correctly like this:
let pets = 2;
let friendsPets = 0;
pets = 4;
let mostPets;
if (pets > friendsPets) {
mostPets = pets
} else if (friendsPets > pets) {
mostPets = friendsPets
}
// Note in this scenario we are ignoring if the variables are the same value, it would be better to just put 'else' without an extra condition.
console.log(mostPets);
Note: As mentioned by @mplungjan, to shorten your code you can change your logic with the following code to get the same result:
let mostPets = Math.max(pets, friendsPets);
Upvotes: 1
Reputation: 177885
You missed an if and you need to declare all the vars and not use let more than once. Let inside curly brackets is only visible in that so-called scope
You mention in a comment you need to use ifs, then If you were to remove the second condition, you do not need the second if:
const pets = 2;
const friendsPets = 0;
let mostPets = pets; // default - could be 0 or nothing (undefined)
if (pets > friendsPets) {
mostPets = pets;
} else {
mostPets = friendsPets;
}
console.log(mostPets);
// OR using the ternary operator;
mostPets = pets > friendsPets ? pets : friendsPets;
console.log(mostPets);
Here is a more elegant version since you are comparing numbers
const pets = 2;
const friendsPets = 0;
let mostPets = Math.max(pets,friendsPets)
console.log(mostPets);
Upvotes: 1