David Linder
David Linder

Reputation: 83

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.

Upvotes: 1

Views: 172

Answers (2)

prasanth
prasanth

Reputation: 22490

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"]))

Upvotes: 0

brk
brk

Reputation: 50291

You are adding ; after every else if which is breaking the code. Also in this line there is no closing "

return names[0] + ", " + names[1] + " and  " + names.length - 1 + "others like this}

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"]))

Upvotes: 1

Related Questions