Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.toUpperCase() is not a function

Tags:

javascript

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);
like image 423
noor Avatar asked Feb 22 '17 14:02

noor


People also ask

Why is toUpperCase not working?

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.

What does the toUpperCase () method do?

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.

What is toUpperCase in JavaScript?

The toUpperCase() method converts a string to uppercase letters. The toUpperCase() method does not change the original string.

What is string :: toUpperCase?

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.


2 Answers

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.

like image 163
3 revs Avatar answered Oct 19 '22 05:10

3 revs


You could apply .toString() first, and then use .toUpperCase():

if (name == name.toString().toUpperCase())
like image 35
Oranit Dar Avatar answered Oct 19 '22 03:10

Oranit Dar