Олег Якунин
Олег Якунин

Reputation: 130

Javascript loop to return string x times

I'm doing Udacity javascript studies now and there is one quiz that bothers me. I know how to do it easily in ruby, but this one is killing me.

I need to call function and return "ha" num times and add "!" at the end with the loop.

I tried this but it didn't help. Should be very simple.

function laugh(num) {
  for (var x = 0; num; x ++) {
      return 'ha';
  }
}

console.log(laugh(3));

Upvotes: 0

Views: 6967

Answers (5)

user2212873
user2212873

Reputation: 81

Returning in a loop will return the whole function. To make this work you could concatenate the string in the loop and then return the concatenated output. You also formatted your loop incorrectly, you need to tell the loop to stop when x is less than num. Try:

function laugh(num) {
  var laughString = '';
  for (var x = 0; x < num; x++) {
    laughString += 'ha';
  }
  return laughString + '!';
}

console.log(laugh(3));

Upvotes: 2

Mbreitling95
Mbreitling95

Reputation: 11

function laugh(input) {
  var answer = '';
  for (var i = 0; i < input; i++) {
    answer += 'ha';
  }
  return (answer + '!');
}

First, set a variable to an empty string, (it will be your answer) Then, write a for loop that loops according to the input (you did that) then inside the for loop you add 'ha' to your answer string finally outside the for loop (after it has ran all the loops) return the answer string plus !

Upvotes: 0

Jarek Kulikowski
Jarek Kulikowski

Reputation: 1389

function laugh(num) {
  var outString = '';
  for (var x = 0; x<num; x ++) {
    outString += ' ha';
  }
  return outString.substring(1) + '!';
}

console.log(laugh(3));

Upvotes: 0

kind user
kind user

Reputation: 41893

Actually you don't even need the loop.

const laugh = num => 'ha'.repeat(num) + '!';

console.log(laugh(3));
console.log(laugh(5));

Upvotes: 5

Bill the Lizard
Bill the Lizard

Reputation: 405735

You can only return once from a function. Try building up the string you need in the loop, then return the value after the loop is done.

(Note: You can have multiple return statements in a function, but as soon as you hit one of them the function completes its execution.)

Upvotes: 1

Related Questions