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
Reasoning
Your “Base Assumption” works because
ais 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
lengthmethod 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’sinstanceofmethod, as follows:Notice that the cases where
instanceof Arrayreturnstrueare 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
charAtfunction. Givenb = 'abcd', performingb[0]is the same as performingb.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.