I am new to JavaScript and I have created this condition to check if the season is Autumn
, Winter
, Spring
, or Summer
.
Here is my JavaScript code:
My question is how to make this in fewer lines of code
How to use both uppercase and lowercase in the same code for eg:
October
andoctober
const seasonName = prompt('entere the month name') if (seasonName == 'september') { console.log("The Season is Autumn.") } else if (seasonName == 'october') { console.log("The Season is Autumn.") } else if (seasonName == 'november') { console.log("The Season is Autumn.") } else if (seasonName == 'december') { console.log("The Season is Winter.") } else if (seasonName == 'january') { console.log("The Season is Winter.") } else if (seasonName == 'february') { console.log("The Season is Winter.") } else if (seasonName == 'march') { console.log("The Season is Winter.") } else if (seasonName == 'april') { console.log("The Season is Spring.") } else if (seasonName == 'may') { console.log("The Season is Spring.") } else if (seasonName == 'june') { console.log("The Season is Summer.") } else if (seasonName == 'july') { console.log("The Season is Summer.") } else if (seasonName == 'august') { console.log("The Season is Summer.") }
CodePudding user response:
I like to take the following approach:
const seasonsByMonth = {
'january': 'winter',
'february': 'winter',
' march': 'winter',
'april': 'spring',
...
}
const seasonName = prompt('entere the month name');
console.log(`The Season is ${seasonsByMonth[seasonName.toLowerCase()]}.`)
CodePudding user response:
Convert the input code to lower or uppercase, then compare. const seasonNameLowercase = seasonName.toLowerCase(); then use the seasonNameLowercase variable in the if conditions, or you can also use switch.
CodePudding user response:
You can use
switch
statement. Code is like this:
switch(seasonName) {
case "september":
case "october":
case "november":
console.log("The Season is Autumn.");
break;
case "december":
case "january":
case "february":
console.log("The Season is Winter.");
break;
case "march":
case "april":
case "may":
console.log("The Season is Spring.");
break;
case "june":
case "july":
case "august":
console.log("The Season is Summer.");
break;
}
CodePudding user response:
You could assign them as objects and use key value pairs to retrieve
// add your months as objects
const seasonObj = {
Autumn: ["september", "october", "november", ],
Spring: ["april", "may"],
summer: ["june", "july", "august"],
Winter: ["december", "january", "february", "march"]
}
function getSeason(value) {
for (const [key, val] of Object.entries(seasonObj)) {
if(val.includes(value))
{
return `the Season is ${key}`
}
}
}
const result = getSeason("april");
console.log(result)