Skip

Can you explain why this works in JavaScript?
September 8, 2012 10:19 AM   Subscribe

Can you explain why this works in JavaScript?

Someone posted this, saying the variable char will be assigned the value "w"

var str="Hello, world!";
var char=str[7];

Since the variable str isn't explicitly defined as an array, and the characters of the string aren't explicitly defined as elements, I didn't believe it would work. But it does!

Can you explain the syntax to me that makes this work? Is any string variable seen as an array by Javascript?
posted by markcmyers to Technology (9 answers total)
 
Is any string variable seen as an array by Javascript?

Yes.
posted by XMLicious at 10:29 AM on September 8, 2012


Because:
0) You assigned str from a static string, so have effectively assigned the type, as well, and...
1) Javascript has insanely loose typing rules, and...
2) Javascript inherits most of its syntax from C, where strings don't exist except as character arrays, and...
3) Strings in JS have an implicit dereference overload (or just plain "load", in this case? What do you call a non-overloaded overload?) on using square brackets.
posted by pla at 10:30 AM on September 8, 2012


Javascript has Duck Typing

The interpreter sees you want to treat the string like an array, and so invokes a string method to treat it as such rather than just throw an error .
posted by TheOtherGuy at 10:30 AM on September 8, 2012


It actually doesn't work in every JS implementation. Older versions of IE, for example (where you'd have to use the .charAt method).

Where it does work, though, it's not so much that Strings are seen as Arrays as that Strings just have an array-like facility for indexing.

There are a couple of other "types" in JavaScript that are like this -- array-like things that are not arrays (function argument lists & DOM nodelists, for example) and therefore may not have *all* the facilities of arrays (particularly all the methods of Array), but have some array-like facilities, including the ability to be indexed with this syntax.
posted by weston at 10:32 AM on September 8, 2012 [1 favorite]


Duck typing. Love it!

Thanks, folks. I can sleep now.
posted by markcmyers at 10:35 AM on September 8, 2012


ECMA-262 edition 5.1, the standard popularly known as "javascript" , specifies this behavior for String objects in 15.5.5.2, "Properties of String Instances / [[GetOwnProperty]] ( P )".
posted by jepler at 10:44 AM on September 8, 2012 [1 favorite]


I don't want to dive into this too much and this may get out of hand but I'm going to argue that this isn't an issue with Javascript's loose type system or even Duck Typing. This is a string being a string

This instead is Syntactic Sugar

For most JS objects you can get its properties via dot notation or bracket notation.

mystring = "hello"
mystring['length'] == 5
mystring.length == 5

Javascript's String Spec (from jepler) has this line

Let resultStr be a String of length 1, containing one character from str, specifically the character at position index, where the first (leftmost) character in str is considered to be at position 0, the next one at position 1, and so on.

which means if instead of doing mystring['some property name'] you do mystring['Some Integer'] it will return the character at that position.

Its something that looks similar to what you're doing to an array which is why it exists but its just grammer its not loose or duck typing. Its more along the lines of the plus sign "+" which does addition when used with numbers but string concatenation when used with strings.
posted by bitdamaged at 10:55 AM on September 8, 2012 [2 favorites]


Don't sleep yet! You've Best-Answered contradictory answers here. XMLicious, pla, and TheOtherGuy are mistaken; the String object is never turned into or treated as an Array.

weston, jepler, and bitdamaged have the correct answer: as described in section 15.5.5 of the ECMAScript (aka JavaScript) specification, the String object overloads the default GetOwnProperty method that does object property lookups so that if the default method returns undefined and the property is a number it returns the character at that position in the string.
posted by nicwolff at 1:13 PM on September 8, 2012 [1 favorite]


I'm always amazed by the erudition of the members of this site, which isn't even focused on coding. I'm happy to have best-answered the early answers even if they aren't bullseyes, because they're close enough for someone like me, but I've got to hand it to the rest of you, some of whom surely have enough knowledge to design your own languages.
posted by markcmyers at 1:41 PM on September 8, 2012


« Older What's a better-security alter...   |  What are the best practices fo... Newer »
This thread is closed to new comments.


Post