Javascript Objects and Javascript Arrays

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.

Analyzing your Javascripts performance

Gone are the days when your Javascript’s performance was no issue, developers used to show more love for their server than client’s browser, scripts used to delay the site loading times. There are many best practices for your JS code like having all your scripts at the bottom, etc. If you are looking for the best practices and approaches for you JS code then you should read Steve Souders, Douglas Crockford, Ben Cherry or google it.

But its not easy to remember all such best practices while you code…

what if you had a tool which would love to review your code and point out all the issues?

Yes this is very much possible, this fantastic tool called JSLint. They call it The Javascript code quality tool. and it is rightly so. You have to paste your JS code on the site and it’ll point out the issues, and guide you to improve the quality, hence improving the performance of you JS.