Search code examples
javascriptstringstring-length

Receiving TypeError: Cannot read property 'length' of undefined - why?


I'm trying to return a simple greeting message which takes an inputted name, whereas if the string is empty will return a generic 'Hello, World!' message. It also looks out for capitalisation errors and will edit the name input to ensure it is properly capitalised. This is what I've got so far.

   function hello(name) {
  if (name.length > 0 && typeof name == 'string') {
    let fixed = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
    return "Hello, " + fixed + "!";
  }
  else {
    return "Hello, World!";
  }
}

It doesn't appear to take the length of the name argument and is the only test it fails on!


Solution

  • first check if is a string

    function hello(name) {
      if (typeof name == 'string' && name.length > 0) { // Changed
        let fixed = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
        return "Hello, " + fixed + "!";
      }
      else {
        return "Hello, World!";
      }
    }