I frequently see code like that:

$("#foo").live("mouseover mouseout", function(e) {
    if (e.type == "mouseover") {
        $("#foo").append("<div id='bar'>");
    } else {

instead of more self-explanatory in my opinion:

$("#foo").live("mouseover", function(e) {
    $("#foo").append("<div id='bar'>");
.live("mouseout", function(e) {

the same goes with

$('#contentPageID, #itemURL').change ( function () {
    if ( $(this).is('#contentPageID') )

does it have any purpose or is it just different coding style (counter intuitive in my point of view) ?

migrated from stackoverflow.com Aug 8 '11 at 3:20

This question came from our site for professional and enthusiast programmers.

  • Why are you using .live :( use .bind or .delegate. Never .live – Raynos Aug 8 '11 at 8:11
  • Just an example taken from someone else's code. I've never used live ;) – Jacek Kaniuk Aug 8 '11 at 8:17

I think you've kind of answered the question yourself.

  • Your first example is a little less readable than your second one.
  • Your third example is horrible - it reminds me of if...elseif...elseif statements which are impossible to debug because the conditions being tested are completely unrelated.

Legibility and maintainability rule. Unless insane performance is the top priority; as dictated by you, your manager, or whoever, go with something that makes you and others happy to read.

// this makes me happy
     click: function() { ... },
     mouseover: function() { ... },
     mouseout: function() { ... }

If you have a lot of shared code between the two flavors and only a little different code, then it can be advantageous to have just one function block and use an if statement in the single block. If the code is entirely different for the two cases, then I'd definitely vote for using two separate jQuery methods because it just seems cleaner to me.

It is, in the end, all personal choice in style. There is no correctness argument one way or the other. One could argue that the single block has only one selector call instead of two, but these are only done once during initialization/setup so it's unlikely that really makes much of a difference.

  • 1
    Better to factor out the shared code into a third method, called from each of the original methods. If the original methods are now trivial, they can be inlined. – kevin cline Aug 8 '11 at 16:51

Your intuition is correct. Conditional statements should be avoided as much as possible. Each conditional doubles the number of paths through a function, and nearly doubles the effort required to understand the function. Functions with conditionals are also more complex to document. If a function is hard to document, it's probably wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.