Search code examples
javascriptarraysreturnreturn-valuereturn-type

Error when trying to return a string with calls from array


This code is returning an error and the 2nd 'else if' statement:

   function likes(names) {

  if (names.length == 0) {
    return "no one likes this"
  } else if (names.length == 1) {
    return names[0] + " likes this"
  };

  // the above is running fine if I remove the second to else if statements. 

  else if (names.length == 2) {
    return names[0] + " and " /*error starts here*/ + names[0] + " like this"
  };
  else if (names.length == 3) {
    return names[0] + ", " + names[1] + " and  " + names[2] + " like this"
  };
  else if (names.lenght > 3) {
    return names[0] + ", " + names[1] + " and  " + names.length - 1 + "others like this};
  }
  console.log(likes(["james", "pete"]))

I guess it's a problem with how I am joining my strings together but I can't seem to figure it out.

Sorry, still learning. Appreciate any feedback.


Solution

  • Problems:

    1. unwanted semicolons in end of each if statement };
    2. And last statement not closing properly with "

    function likes(names) {
    
      if (names.length == 0) {
        return "no one likes this"
      } else if (names.length == 1) {
        return names[0] + " likes this"
      } else if (names.length == 2) {
        return names[0] + " and " /*error starts here*/ + names[0] + " like this"
      } else if (names.length == 3) {
        return names[0] + ", " + names[1] + " and  " + names[2] + " like this"
      } else if (names.lenght > 3) {
        return names[0] + ", " + names[1] + " and  " + (names.length - 1) + "others like this"
      }
    }
    console.log(likes(["james", "pete"]))