Javascript functions help

im currently doing a bootcamp assignment and ive been googling and cant figure out the
correct solution to this can someone help me please heres the problem

Write a function that takes two parameters, word and n, as arguments and returns the word concatenated to itself n number of times. (i.e. if I pass in ‘Hello’ and 3, I would expect the function to return ‘HelloHelloHello’).

ive tried all of these different solutions what am i doing wrong ive even looked on youtube

function pere(word, n) {
    return word * n;

}

console.log(pere("hello", 10));





function pere(word, n) {
    return word * n;

}

console.log(pere("hello",)(10));

function pere(word, n) {
   console.log(word * n);

}

 pere("hello", 10));

@devonz, the issue is that you’re using the multiplication (*) operator to concatenate the word. This is not possible as * only works on numeric values for multiplication as mentioned here.
If you want to concatenate string values, check out the concat method

But it says I would have to return the word concatenated into itself n number of times . How would the concat method do that if there is a number passed in . Were you able to read the question fully ?

You can start with an empty string, and loop n times, keep concatenating the word in each iteration of the loop.
You could also use the addition (+) operator for string concatenation instead of the concat method.

1 Like

I tried the addition operator it just returns the word and a number next to it it doesn’t return the word multiple times.

You need to have a loop inside the function that will be executed n times.
and as it was explained above:

  • declare an empty string (a container)
  • Execute a loop (like for) that will iterate n times,
  • push the string to the container in each iteration.
  • Return the container after the loop execution;
    good luck.
1 Like

I figured out the solution already but thanks for the tips anyway.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.