Skip to content Skip to sidebar Skip to footer

Why Is This Loop Using Function Parameter Returning Only Once?

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 arg

Solution 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));

Solution 2:

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;
};

Solution 3:

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;
};

Post a Comment for "Why Is This Loop Using Function Parameter Returning Only Once?"