-3

So, I am learning functions and trying to create a function which takes an array as a parameter.

function printArray(arr){
    for (let i = 0; i < arr.length; i++){
        let upperCased = arr[i].toUpperCase();
        return upperCased;
    };
}
const testArray = ['o', 'p'];
printArray(testArray);

However, it returns only the first value 'O'

2 Answers2

0

A return statement only gets executed once, then you exit the function.

Dennis Kozevnikoff
  • 1,654
  • 3
  • 14
  • 24
0

You need to update the element on each iteration and, once the loop is complete, return the updated array.

function printArray(arr) {
  for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i].toUpperCase();
  }
  return arr;
}

const testArray = ['o', 'p', 'Bob from accounting'];

console.log(printArray(testArray));
Andy
  • 53,323
  • 11
  • 64
  • 89