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'
A return statement only gets executed once, then you exit the function.
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));