1

This question actually is an outcome from another question, for which i have made some experiments, results are confused me more. I'm expecting answers which explains what actually happens internally.

What i have tried is,

I kept this as the base assumption because i got some clear explanation here,

var a = [];
a['a1'] = [];
a['a2'] = [];

console.log(a); // []
console.log(a['a1']); // []
console.log(a['a2']); // []

TEST 1

This confused me a lot, since it prints b[0] as a and can be able to access length property, i thought var b can be treated as a character array, therefore i tried to assign another value , but ended up without success. From the base assumption, if this one can be treated as a char array(more generally as an array), the assignment should have been successful. It breaks the base assumption.

var b = 'abcd';
b['b1'] = [];

console.log(b); // abcd
console.log(b.length); // 4
console.log(b['b1']); // undefined

TEST 2

But if i create like this, the assignments are happens,

var bb = ['a', 'b', 'c', 'd'];
bb[4] = [];

console.log(bb); // ["a", "b", "c", "d", []]
console.log(bb.length); // 4
console.log(bb[0]); // a
console.log(bb[4]); // []

From this, i thought that, b[4] = []; may be successful, but

var b = 'abcd';
b[4] = [];

console.log(b); // abcd
console.log(b.length); // 4
console.log(b[4]); // undefined

My question is, why these assignments behaving differently while the variables sharing some common functionalities?

Here is the demo

Can anyone please give me a clear cut explanation about what actually happening internally?

Extra tests

Then if i tried with numerical assignment, it behaves quite differently form those two.

var c = 1234;
c[4] = [];

console.log(c); //1234
console.log(c.length); // undefined
console.log(c[0]); //undefined
console.log(c[4]); //undefined   
2
  • You are assuming that a string is a character array. It is not, so nothing you derive from that assumption is guaranteed to work.
    – JJJ
    Aug 15, 2012 at 16:26
  • @Juhana not at all, assumed, can be treated as a char array since the results confused.
    – code-jaff
    Aug 15, 2012 at 17:23

4 Answers 4

1

When you access anything but an object with [], a temporary object instantiated with correct prototype (like String or Number) is provided for you. You can read and write properties of this object as you could with any other - try alert(3["constructor"]) for example. However, since this object is not referenced anywhere it goes to garbage right after you've done indexing it and next time you try to read same property you've just set, you're actually accessing a property on new temporary object, which, naturally, is empty.

1

Test 1: b is a string internally, not an array, so you can't assign something in a b position.

Test 2: Off course it works, since now bb is an array.

My question is, why these assignments behaving differently while the variables sharing some common functionalities?

Because their types are different.

Test 3: c is a Number, not an array.

Maybe you have some C background, where strings are char arrays terminated by a null char (\0). In JavaScript strings are built int types and they behave differently of arrays. The [] operator is just a convenience to access one especific char as Jonathan said. Here are some links, take a look:

1
  • there is as small typo in the second line b should be bb
    – code-jaff
    Aug 16, 2012 at 3:10
0

Reasoning

Your "Base Assumption" works because a is an array. "Test 2" is the only other test case that you have written that uses an array, which is why that is the only other test case that works.

You seem to be assuming that providing a square-bracket notation and having a length method indicates that an object is an array. This is not true. To test to see if an object is an array, you can use JavaScript's instanceof method, as follows:

var a = [];
var b = 'abcd';
var bb = ['a', 'b', 'c', 'd'];
var c = 1234;

a  instanceof Array // => true
b  instanceof Array // => false
bb instanceof Array // => true
c  instanceof Array // => false

Notice that the cases where instanceof Array returns true are the ones that are acting as you expected, since you are trying to perform array operations.


Why "Test 1" Failed

For "Test 1", square-bracket notation for strings performs the string class's charAt function. Given b = 'abcd', performing b[0] is the same as performing b.charAt(0). It is read-only and simply returns the character at that index, which is "a".

See the Mozilla Developer Network documentation for Strings for more details.


Why "Extra Test" Failed

For your "Extra Test", integers do not provide a square-bracket notation or a length method, and thus all of those calls failed.

2
  • I accept the reasoning, but what i'm wondering is, if b or c not a type of array, then how the assignments were successful, even not throw any exception.
    – code-jaff
    Aug 15, 2012 at 17:16
  • They didn't fail. While literals don't provide properties, auto-instantiated object do. Try alert(42["constructor"]). Those calls didn't fail, it is simply that Number instances don't have any meaningful data on numeric properties. Also, square brackets are used to index any object, it is not exclusive to array. Aug 16, 2012 at 9:01
0

I guess I don't follow what your question is. Javascript treats strings, arrays, and integers differently. You should not expect them to behave in the same manner. Also there is no such thing as associative arrays in javascript to where your first example would work. The a['a1'] type of notation is actually only an alternative means for accessing object properties and have no meaning in the context of a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.