-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'

Chukwuemeka
  • 56
  • 1
  • 5

2 Answers2

0

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

Dennis Kozevnikoff
  • 2,078
  • 3
  • 19
  • 29
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
  • 61,948
  • 13
  • 68
  • 95