Jim Moody Jim Moody - 1 year ago 82
Javascript Question

How do I assign a conditional variable without mutation?

I am adhering to strict functional programming principles with no mutation.

How can I write something like the below code in a way that doesn't mutate the

greeting
variable, and without returning it within each
if
block?

const greet = (name, time) => {
let greeting = 'Morning';

if(time >= 12) {
greeting = 'Afternoon';
}
if(time >= 17) {
greeting = 'Evening';
}

return `Good ${greeting} ${name}!`;
};


If it was just two conditions I would do the following, but it won't work when there are 3 conditions:

const greeting = time > 12 ? 'Afternoon' : 'Morning'

Answer Source
const greeting = time > 12 ? (time > 17 ? 'Evening' : 'Afternoon') : 'Morning'

However, i think its the variable that makes the variable a variable...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download