0

Possible Duplicate:
string.charAt(x) or string[x]?

It seems that "asdf"[0] produces "a". So why would anyone ever type out "asdf".charAt(0)?

Is that shorter syntax safe to use?

Cross browser compatibility? That's about all I can think of.

Community
  • 1
  • 1
wwaawaw
  • 6,867
  • 9
  • 32
  • 42
  • http://stackoverflow.com/a/5943760/303270 – fardjad Sep 22 '12 at 13:51
  • Once difference is that `charAt` will return an empty string if the index is out of bounds, whilst `str[x]` will return undefined if `x` is out of bounds. – David G Sep 22 '12 at 13:54

4 Answers4

4

You can only access strings as arrays in newer browsers. To support older browsers (i.e. IE7) you have to use charAt.

Related: string.charAt(x) or string[x]?

Community
  • 1
  • 1
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

I think it makes for cleaner, more readable code. If you use

foo.charAt(0) 

instead of

foo[0] 

(an array index), you make it clear that foo is a string, not an array. Also, you are less likely to use other array methods that may fail.

Addendum

Because some people aren't clear what I mean, let me say that again: Other array methods may fail when used on a String.

Try it yourself:

var foo = "This is a string.";
foo.push(" A string is not an array.");

You will get a TypeError.

And for those who may confuse array notation with bracket notation, try the following experiment. Open up your browser's console and enter the following:

foo = {bar:'ass',fub:'tree',mip:0};

Now try to access the first element with bracket notation:

foo['bar'] returns "ass";

foo[0] returns undefined.

Robusto
  • 31,447
  • 8
  • 56
  • 77
  • It also makes it clearer that you cannot change the value of that character. – jonvuri Sep 22 '12 at 13:58
  • Considering all the languages where `str[idx]` is supported but don't support any other array functionality, I cannot agree with this. –  Sep 22 '12 at 14:03
  • 1
    You can use array notation on any object in Javascript, for example `foo['charAt'](0)` instead of `foo.charAt(0)`, so using brackets shouldn't automatically make you think that a variale is an array. – Guffa Sep 22 '12 at 14:12
  • @Guffa: I'm not talking about array notation. Note that I said "array **methods** may fail" when used on a `String`. Try using `Array.push()` or `Array.pop()` on a `String` and you will get a TypeError. – Robusto Sep 23 '12 at 00:08
  • @Robusto: You are missing the point. Array notation can be used on any object, so using array notation on a variable shouldn't automatically make you think that the variable is an array. – Guffa Sep 23 '12 at 08:04
  • @Guffa: I think you're confusing array notation with bracket notation. If I create an object like so: `var foo = {bar:'ass',fub:'tree',mip:0};` I can access its first element as `foo['bar']` or `foo.bar` but I *can't* (at least in the Webkit browser I'm using right now) access it with `foo[0]`. That returns `undefined`. – Robusto Sep 23 '12 at 10:46
  • @Robusto: There is no difference. Using `foo[0]` gives exactly the same result as `foo['0']`. If you create the object `var foo = { '0': 1, '1': 2, '2': 3 };` both `foo[0]` and `foo['0']` returns `1`, and `foo.bar` return `undefined` just as `foo['bar']`. – Guffa Sep 23 '12 at 11:00
  • @Guffa: That's even more confusing for people trying to read code, and a worse coding practice. It only works with integers, because Javascript coerces the `'0'` behind the scenes into a `0`. I still maintain that accessing a string that way may cause future developers to think a variable is an array that can use array methods. If you want to confuse people down the road, by all means write ambiguous code. – Robusto Sep 23 '12 at 11:05
  • @Robusto: You are completely missing the point. Again. I wasn't showing anyting that you *should* do, I was showing how arrays and objects work the same. If you really don't want to understand, then feel free not to. – Guffa Sep 23 '12 at 11:08
  • @Guff: Your initial comment on my answer seems to take issue with my contention that using "array notation" on a string is ambiguous. You said it "shouldn't automatically make you think a variable is an array," which sounds like you're arguing that it's perfectly all right to do so. Now you argue that you weren't "showing anything that [a person] should do," which is a disclaimer that militates against your earlier assertion. I am left wondering what your point is. The OP wanted a reason to use `String.charAt()`. I gave him one. You misled him with an "older browsers" dodge, which he accepted. – Robusto Sep 23 '12 at 12:26
  • @Robusto: You are mixing up what I am answering to, and try to put words in my mouth that I have never written. When I said that I wasn't showing anything that one should do, I was refering to the example directly before that, nothing else. I don't know why you think that I was misleading someone with my answer. You should really explain what you think is misleading with answer that is based on a well documented fact. – Guffa Sep 23 '12 at 22:24
0

Cross-browser compatibility is an issue. When I pop open IE9's console and set it to IE7 standards, "a"[0] produces undefined while "a".charAt(0) works as expected.

ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152
0

Most browsers indeed allow you to treat string as an array of chars (just like it works in many other programming languages).

IE, on the other hand, does not. There, you must use "asdf".charAt(0).

Now I would say that allowing the [] notation is just an extra option browsers allow you, to make strings behave similar to languages like C, Pascal, etc. However, strings in Javascript are actually not arrays and thus by standard should not work with []. Strings are built-in classes, so to access their properties you have to use their public methods, like in Java.

Imp
  • 8,409
  • 1
  • 25
  • 36