I came across some interesting facts regarding Javascript Objects and Javascript Arrays which I will be discussing below.
Most of us are familiar with Javascript objects and arrays. Technically Javascript Arrays are also Javascript objects, even the typeof Javascript Array will also give its type as object and not array
typeof is a simple JS operator which returns typeof the element passed.
But there are some tiny , interesting and somewhat buggy aspects of Javascript arrays.
- If in a Javascript Array, you set index 100 to have any value then the length of this array will be returned as 101. JS will fill the rest 100 keys (0 – 99) with null values
Try this :var test_array = Array(); test_array.length; //returns 0 this time test_array[100] = 'I am hundred'; test_array.length; //returns 101 now
- Javascript Arrays cannot ideally be treated as Associative Arrays. You can set and access associative keys but when you do so Javascript arrays work 100% as JS objects and the length of the array wont increase no matter ho many associative keys and respective values you keep on adding.
var test_array = Array(); test_array.length; //returns 0 this time test_array['key1'] = 'I am key 1'; test_array['key2'] = 'I am key 2'; test_array.length; //again 0
- The fact above also concludes that JS objects dont have any length property, so we cannot determine whether an object is empty or not with the length property.