Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between size() and length in Javascript

    • 0
    • 3
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 1.72k
    Comment on it

    In jQuery size() and length property are the two features, which have the same property of returning the number of elements in a jQuery object which creates a lot of confusion for developers.

    This blog is to help developers to understand the difference between these two functions.

    While using any of these function a developer must be aware of the following points :

    1. length is a property which works faster as compared to size() function, the reason behind this is that the length is a property and size is a function and we know that any property works faster than any function or method.

    2. Indirectly size() also does the same thing i.e it returns length which length can do directly, without using an extra method call that's why length is slightly faster than size().

    3. Using size() is a long way of returning the number of elements in a jQuery object as whenever size function is called it reads the length property and then returns the number of elements whereas length property is a short way because once it is read, after that whatever time is required is the time required for accessing an object. 

    4. There is one more difference which is not noticed but it creates a difference, length is referred to the number of elements and 'size' is always referred to the number of bytes due to which size is considered as greater as compared to a length of any data types except char datatype of the array.

     

    Following is the syntax and example of size and length
    Note:Please include this link in your file

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

     

    Syntax of size():

    $(selector).size();

     

    Example of jquery size() function:

    <script>
    $(document).ready(function(){
        $("ul").click(function(){
            alert($("ul li").size());
        });
    });
    </script>

     

    Syntax of jquery.length:

    $(selector).length;

     

    An example of length property.

    <script>
    $(document).ready(function(){
        $(".calOne").click(function(){
            alert($(".cal li").length);
        });
    });
    </script>

    Hope this will make you understand the difference.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: