Search code examples
javascriptprototypestring-length

How is it possible for an empty string to have a length greater than 0?


I came across this bug while trying to run a JS conditional to check for an empty string. In Chrome debugger, the empty string evaluates with a length of 1 and sometimes even 2. It's happening in a react app. I'm pretty lost as to how the proto still works correctly but the normal length method doesn't.

enter image description here


Solution

  • A string may appear visibly empty when you ask for its value if the string contains characters that are not normal characters. These strings could be generated via the String.fromCharCode method or implicitly like '\x0d'. Characters such as Enter will appear to be an empty string. You can check for invisible characters using the charCodeAt method.

    As Matus showed, this will replicate the behavior in question:

    v = '\x0d'
    
    console.log(v);        // ""
    console.log(typeof v); // "string"
    console.log(v[0]);     // "" 
    console.log(v.length); // "1"