Search code examples
javascriptjqueryarraysarray-push

Jquery push function


I'm working on samsung SDK and modifying a javascript app for smart tv. I stumbled upon this piece of code and I don't understand what if($('.menuButton').push()){... does. The native push function was not overwrited but this still works. I thought push will append an element to an array, but this doesn't seem to be the case

if(direction==tvKey.KEY_ENTER){
        if($('.menuButton').push()){
            $('.simple_menu').slideDown('easy');
     ........

Solution

  • Calling .push(x) on a JQuery selector acts the same as calling .push(x) on a normal array in Javascript.

    From W3Schools and the Mozilla Developer Network:

    The push() method adds new items to the end of an array, and returns the new length.

    and

    Returns: The new length property of the object upon which the method was called.

    If no arguments are passed to .push(), then the array is left as-is, and the length is still returned. So what is happening here is the array length is being returned and used to evaluate the if statement.

    Example: The following will return the number of p tags:

    $("p").push();
    

    But Beware: The .push method for JQuery objects is marked for internal use only and thus should not be depended on.