How do I assign a conditional variable without mutation?

Viewed 1299

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'
6 Answers

To be clear you are not doing any mutation, you are using let instead of const. Why it is not a mutation - because string is immutable in javascript. So your question is more - "How assign conditional value to const".

To be clear I don't see anything wrong with doing let here and such behavior. Until this not goes outside the function scope it is just fine to mutate it (I am talking more about general approach, for example with objects).

Immutability rule should be used for structures declared outside the scope of the function. What directly means that you should never mutate function input and never touch what not belongs to you.

To the point, my answer is - leave it as it is, for me it is much more clear than ternary operator with many conditions.

Related