The terminal gave me a type error that the method I was using (.toUpperCase) on a function is incorrect. So are methods not meant to be used on functions?
You haven’t linked to the exercise/challenge. But based on the parameter name arr
, I assume that the expected argument is supposed to be an array of strings.
The toUpperCase
method can be used with a string, but you can’t apply the toUpperCase
method directly on an array. You must iterate over the array and call the toUpperCase
method on each string.
In your screenshot,
// Your function:
function shoutGreetings(arr) {
console.log(arr.toUpperCase() + '!')
}
let word = "hello";
let myArray = ["hello", "there"];
shoutGreetings(word);
// Output: "HELLO!"
shoutGreetings(myArray);
// TypeError
To add onto that, if you wanted to upper case every word in an array, as mtrtmk mentioned, you’d have to loop through it somehow. You could either create a standard for loop, or use something like .map() or .forEach() - i.e…
function shoutGreetings(arr) {
arr.forEach(greeting => console.log(greeting.toUpperCase() + "!")
}
const greetingsArray ['hello', 'bonjour', 'hoi']
shoutGreetings(greetingsArray)
// logs 'HELLO', 'BONJOUR', and 'HOI'
This will perform the desired function of logging to the console every item in the array provided with the transformation of the .toUpperCase() method.
Thank you, now I understand it.