When name is all uppercase, then the function should shout back to the user. For example, when name is "JERRY" then the function should return the string "HELLO, JERRY!" The console logs error: .toUpperCase() is not a function.
var hello = "Hello, ";
function greet(name) {
if (name == null) {
console.log(hello + "my friend")
} else if (name == name.toUpperCase()) {
console.log(hello.toUpperCase() + name.toUpperCase())
} else {
console.log(hello + name);
}
}
var names = ["jack", "john"]
greet(names);
The "toUpperCase is not a function" error occurs when we call the toUpperCase() method on a value that is not a string. To solve the error, convert the value to a string using the toString() method or make sure to only call the toUpperCase method on strings.
Description. The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable.
The toUpperCase() method converts a string to uppercase letters. The toUpperCase() method does not change the original string.
Java String toUpperCase() Method The toUpperCase() method converts a string to upper case letters. Note: The toLowerCase() method converts a string to lower case letters.
names
is an array. An array has no such function.
You probably want to call the greet
function on every element of the array:
names.forEach(greet);
If you want the greet
function to accept an array as argument then you could do
function greet(name) {
if (Array.isArray(name)) {
name.forEach(greet);
return;
}
...
but this kind of polymorphism is usually seen as a bad practice.
You could apply .toString()
first, and then use .toUpperCase()
:
if (name == name.toString().toUpperCase())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With