DEV Community

Discussion on: Why you shouldn't reassign values in JavaScript

Collapse
 
dallgoot profile image
dallgoot
function getHairType (today) {
  switch(today.toLowerCase()){
    case "monday":    return 'bangs';
    case "tuesday":   return 'braids';
    case "wednesday": return 'short hair';
    case "thursday":  return 'long hair';
    case "friday":    return 'bright pink hair';
    default:
        //default value or throw "only workdays allowed for 'today'"
  }
}

or to allow rapid visualisation of constants:

const MONDAY_HAIRTYPE = 'bangs';
// ... const for each day
const DEFAULT_HAIRTYPE = MONDAY_HAIRTYPE; 

let dayHairType = today.toUpperCase()+"_HAIRTYPE"; 
hair = dayHairType in this ? this[dayHairType] : DEFAULT_HAIRTYPE;

no undefined, no function call cost