Reputation: 1
Hello I am new to JavaScript I am trying to get season name when user enters a month name. What am I doing wrong?
const takeInput = prompt("Enter the Season Name : ");
let seasons = {
summer: ["may", "june", "july"],
winter: ["november", "december", "january"],
};
takeInput.toLowerCase();
switch (takeInput) {
case "summer":
if (takeInput === seasons.summer) {
console.log("summer");
}
break;
}
Upvotes: 0
Views: 273
Reputation: 68
try this:
//instead of
if (takeInput === seasons.summer) {
console.log("summer");
}
//do this:
if(seasons.summer.find(season => season === takeInput)){
console.log("summer")
}
Upvotes: 0
Reputation: 3829
takeInput === seasons.summer
Here you're checking if the takeInput is equals to seasons.summer but the fact is that the takeInput is a string
whereas seasons.summer
is an array.
Then it will always return false
You're also combining a switch
with and if
. This is the wrong way of doing it. In fact, the switch will be equivalent to an if/else if/else
.
For example :
const number = 1;
switch(number){
case "1":
console.log("odd")
break;
case "2":
console.log("even")
break;
default:
console.log('something else')
break;
}
is equivalent to
const number = 1;
if(number === 1){
console.log("odd")
} else if (number === 2){
console.log("even")
} else {
console.log('something else')
}
In your case, i thing you're looking for this :
const takeInput = prompt("Enter the Season Name : ");
let seasons = {
summer: ["may", "june", "july"],
winter: ["november", "december", "january"],
};
switch (takeInput.toLowerCase()) {
case "summer":
console.log("summers");
console.log("month", seasons.summer)
break;
}
Note : If you want to find the season by month. You can do it like this :
const takeInput = prompt("Enter the Month Name : ");
let seasons = {
summer: ["may", "june", "july"],
winter: ["november", "december", "january"],
};
Object.entries(seasons).forEach(([key, value]) => {
if(value.includes(takeInput.toLowerCase())) console.log(key)
})
Upvotes: 1