1

I know that there are better ways to check for an empty string—bear with me.


This is not checking for empty string in general. I'm actually doing something like:

var s = /*who knows?*/;
switch (s.charAt(0)) {
    // ...
}

and wanted to know if I can avoid having to do an extra if (!s).

Aaron Yodaiken
  • 19,163
  • 32
  • 103
  • 184

3 Answers3

4

Yes, as long as the value is a valid string. Section 15.5.4.4 of the language spec says

  1. Let position be ToInteger(pos).
  2. Let size be the number of characters in S.
  3. If position < 0 or position ≥ size, return the empty String.

That was not changed since ES3. Interpreters are pretty good around string function compatibility.

That said, I recently implemented a peephole optimization for charAt to Closure compiler but I did not optimize out of bounds checks because the compiler tends not to optimize what are considered programmer errors.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
3

Yes, it will always return "" if the index exceeds the length of the string.

Taken from MDC's documentation of the charAt() function:

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called stringName is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.

Matt
  • 74,352
  • 26
  • 153
  • 180
2

To answer the modified question (or what I think the question is):

If your variable is undefined or not of type string, then .charAt will fail.

Do something like

if (typeof s == "string") {
    switch(s) {
        //...
    }
}
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
  • 1
    Or using the `===` operator to avoid type conversions. (An empty string will also compare equal to false, empty list, zero, and whatever else given the weird conversion rules.) – millimoose Nov 23 '11 at 15:28
  • `switch ("string" === typeof s && s.charAt(0))` will also work. The `default` case will fire when `s` is not a string. – Mike Samuel Nov 23 '11 at 19:23