-1
const alphabets= {
  first: ["a", "b", "c"],
  second: ["d", "e", "f"],
  third: ["g", "h"]
};    

function trial(arr) {

  for (let i = 0; i < arr.length; i++) {
    const argh = `<li class = "text-warning">${i}<li>`;
    return argh;
  }
};

console.log(trial(alphabets.second));

I've tried the same 'for loop' outside the function replacing condition with a number and it works fine. Why is it only looping once when put in the function and using the parameter in the condition?

NewLearner
  • 13
  • 1

3 Answers3

1

Because the return statement will stop your function. Maybe you want to concatenate a string before returning it?

function trial(arr) {

  let returnValue = '';

  for (let letter of arr) {
    returnValue += `<li class = "text-warning">${letter}<li>`;
  }

  return returnValue;
};
Guerric P
  • 30,447
  • 6
  • 48
  • 86
1

If you'd like an array, you could push to an array and then return after the loop is done.

function trial(arr) {
  const argh = [];
  for (let i = 0; i < arr.length; i++) {
    argh.push(`<li class = "text-warning">${i}<li>`);
  }
  return argh;
};
Nick
  • 16,066
  • 3
  • 16
  • 32
1

return

The return statement ends function execution and specifies a value to be returned to the function caller.

You can declare the variable outside the for loop and concatenate the htmlString in each iteration and return the variable after the loop completion.

const alphabets= {
  first: ["a", "b", "c"],
  second: ["d", "e", "f"],
  third: ["g", "h"]
};    

function trial(arr) {
  let argh='';
  for (let i = 0; i < arr.length; i++) {
    argh += `<li class = "text-warning">${i}<li>`;
  }
  return argh;
};

console.log(trial(alphabets.second));
Guerric P
  • 30,447
  • 6
  • 48
  • 86
Mamun
  • 66,969
  • 9
  • 47
  • 59