[Solved] refactoring/making the code better in javascript [closed]


Yes, you should use switch statement here. Chaining so many else if’s is considered bad practice.

You can read about switch statement here. https://www.w3schools.com/js/js_switch.asp

Code would look something like:

function likes(names) {
    if(names.length<0) {
         return `${names} likes this`; //return early if possible
    }
    let answer="";
        switch (names.length) {
          case 0:
            answer = `no one likes this`;
            break;
          case 2:          
            answer = `${names[0]} and ${names[1]} like this`;
            break;
          case 3:
            answer = `${names[0]}, ${names[1]} and ${names[2]} like this`;
            break;
          case 4:
          default:
            answer = `${names[0]}, ${names[1]} and ${names.length-2} others like this`;      
        }
    
    return answer;
}

2

solved refactoring/making the code better in javascript [closed]