This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes HTML, CSS and JavaScript and the fly likes Checking for postive length of jQuery wrapped set before calling methods on set Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Checking for postive length of jQuery wrapped set before calling methods on set" Watch "Checking for postive length of jQuery wrapped set before calling methods on set" New topic
Author

Checking for postive length of jQuery wrapped set before calling methods on set

Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1747
    
    2
I've come across some jQuery code that checks the length of the wrapped set before performing certain "getting rid of" methods, such as hide() or remove(). Presumably, the coder's intent is only to call hide() or remove() if there's actually something matched to hide or remove.



Elsewhere in the same code (presumably written by the same person, or team), there's no length check before other operations:



Are such length checks necessary? If so, why?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61315
    
  66

Not necessary. If there's nothing in the set, the methods will be a noop.

Building the wrapped set twice is also an unnecessary performance hit.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1747
    
    2
Bear Bibeault wrote:Not necessary. If there's nothing in the set, the methods will be a noop.


That's what I was thinking. I wondered if it stemmed from a fear of calling a method on a null, but a set is returned, albeit empty.

Bear Bibeault wrote:Building the wrapped set twice is also an unnecessary performance hit.


Yes! In this example, I'm guessing the set is not a very expensive one to build, but in the general case, why would you do it twice.

Thanks for the confirmation.

Mike "off to fight crime" Matola
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61315
    
  66

Michael Matola wrote:Mike "off to fight crime" Matola

What color is your cape?
Michael Matola
whippersnapper
Ranch Hand

Joined: Mar 25, 2001
Posts: 1747
    
    2
Invisible.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61315
    
  66

Ah, The Stealth Superhero.
 
GeeCON Prague 2014
 
subject: Checking for postive length of jQuery wrapped set before calling methods on set