Manuel
Manuel

Reputation: 37

Javascript for loop only runs once

Why does this for loop run only once? i put the increments but it only returns the last letter of the first element in the array and not the other one.

function lastChars(arr){
  for( let i=0;i<arr.length;i++){
    let letter=arr[i].slice(-1);
    return letter  
  }
}
console.log(lastChars(['the','book']))

It prints just e and not k as well.

Upvotes: 0

Views: 98

Answers (2)

David
David

Reputation: 218808

The function returns on the first iteration of the loop, thus ending the execution of the function:

for( let i=0;i<arr.length;i++){
  let letter=arr[i].slice(-1);
  return letter // <--- here
}

If you're looking to aggregate multiple letters and return all of them, you might do something like put them into an array and return the array after the loop:

let letters = [];
for( let i=0;i<arr.length;i++){
  letters.push(arr[i].slice(-1));
}
return letters;

Which itself can just be simplified to:

return arr.map(a => a.slice(-1));

For example:

const lastChars = arr => arr.map(a => a.slice(-1));
console.log(lastChars(['the','book']))

Upvotes: 1

yoshivda
yoshivda

Reputation: 55

Inside your for loop, you have a return statement. The first time it hits that, the function will return that value. In other words, the function stops before even getting to the second part of the loop.

You may want to print the character instead, or add it to a list, so you can return that after the loop is done.

Upvotes: 2

Related Questions