Swasbuckler-27
Swasbuckler-27

Reputation: 73

Javascript error while concatenating values

I'm attempting a Javascript challenge on the 'codewars' website where the instructions are:

Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"
For more than 4 names, the number in and 2 others simply increases.

My attempt is this:

function likes(names) {
  var response = "a"
  console.log(names[0]);
  if (names.length === 0) {
    response = 'no one likes this';
  }
  else if (names.length === 1) {
    response = names[0] +' likes this';
  }
  else if (names.length === 2) {
    response = names[0] + ' and' + names[1] ' like this';
  }
  else if (names.length === 3) {
    response = names[0] + ',' + names[1] + ' and' + names[2] + ' like this';
  }
  else {
    response = names[0] + ',' + names[1] + ' and' + (names.length-2).toString() + ' others like this';
  }
  return response;
}

and returns this error:

kata: Unexpected token:44 response = names[0] + ' and' + names[1] ' like this';

is it not possible to concatenate a string value inside an array with another string? Any help would be much appreciated.

Upvotes: 0

Views: 121

Answers (2)

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

You are missing + sign here

response = names[0] + ' and' + names[1] ' like this';

Try like this

response = names[0] + ' and' + names[1] +' like this';

Upvotes: 5

cviejo
cviejo

Reputation: 4398

You forgot a + on this line:

response = names[0] + ' and' + names[1] + ' like this';

Not critical but you also forgot a ; and the ' and' should be ' and '

function likes(names) {

    var response = "a";

    if (names.length === 0) {
        response = 'no one likes this';
    } else if (names.length === 1) {
        response = names[0] + ' likes this';
    } else if (names.length === 2) {
        response = names[0] + ' and ' + names[1] + ' like this';
    } else if (names.length === 3) {
        response = names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this';
    } else {
        response = names[0] + ', ' + names[1] + ' and ' + (names.length - 2).toString() + ' others like this';
    }
    return response;
}

Upvotes: 1

Related Questions