Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3235594
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T17:31:28+00:00 2026-05-17T17:31:28+00:00

NOTE: Updated and rewritten This question has been redone and updated. Please pardon outdated

  • 0

NOTE: Updated and rewritten

This question has been redone and updated. Please pardon outdated references below.
Thanks.

I’ve seen a lot of javascript code lately that looks wrong to me. What should I suggest as a better code pattern in this situation? I’ll reproduce the code that I’ve seen and a short description for each one:

Code block #1

This code should never evaluate the inner function. Programmers will be confused because the code should run.

$(document).ready( function() { 
  return function() { 
    /* NOPs */
  }
});

Code block #2

The programmer likely intends to implement a self-invoking function. They didn’t completely finish the implementation (they’re missing a () at the end of the nested paren. Additionally, because they aren’t doing anything in the outer function, the nested self-invoking function could be just inlined into the outer function definition.

Actually, I don’t know that they intend a self invoking function, because the code is still wrong. But it appears they want a self invoking function.

$(document).ready( (function() { 
  return function() { 
    /* NOPs */
  }
}));

Code block #3

Again it appears the programmer is trying to use a self-invoking function. However, in this case it is overkill.

$(document).ready( function() { 
  (return function() { 
    /* NOPs */
  })()
}); 

Code block #4

an example code block

$('#mySelector').click( function(event) { 
  alert( $(this).attr('id') );

  return function() { 
    // before you run it, what's the value here?
    alert( $(this).attr('id') );
  }
});

Commentary:

I guess I’m just frustrated because it causes creep bugs that people don’t understand, changes scoping that they’re not grokking, and generally makes for really weird code. Is this all coming from some set of tutorials somewhere? If we’re going to teach people how to write code, can we teach them the right way?

What would you suggest as an accurate tutorial to explain to them why the code they’re using is incorrect? What pattern would you suggest they learn instead?


All the samples I’ve seen that have caused me to ask this question have been on SO as questions. Here’s the latest particular snippet I’ve come across that exhibits this behavior. You’ll notice that I’m not posting a link to the question, since the user appears to be quite the novice.

$(document).ready(function() {
 $('body').click((function(){
  return function()
  {
   if (counter == null) {
    var counter = 1;
   }
   if(counter == 3) {
     $(this).css("background-image","url(3.jpg)");
     $(this).css("background-position","10% 35%");
     var counter = null;
   }
   if(counter == 2) {
     $(this).css("background-image","url(2.jpg)");
     $(this).css("background-position","10% 35%");
     var counter = 3;
   }
   if(counter == 1) {
     $(this).css("background-image","url(1.jpg)");
     $(this).css("background-position","40% 35%");
     var counter = 2;
   }


  }
 })());
});

Here’s how I proposed that they rewrite their code:

var counter = 1;
$(document).ready(function() {
    $('body').click(function() {
        if (counter == null) {
            counter = 1;
        }
        if (counter == 3) {
            $(this).css("background-image", "url(3.jpg)");
            $(this).css("background-position", "10% 35%");
            counter = 1;
        }
        if (counter == 2) {
            $(this).css("background-image", "url(2.jpg)");
            $(this).css("background-position", "10% 35%");
            counter = 3;
        }
        if (counter == 1) {
            $(this).css("background-image", "url(1.jpg)");
            $(this).css("background-position", "40% 35%");
            counter = 2;
        }
    });
});

Notice that I’m not actually saying my code is better in any way. I’m only removing the anonymous intermediary function. I actually know why this code doesn’t originally do what they want, and I’m not in the business of rewriting everyone’s code that comes along, but I did want the chap to at least have usable code.

I thought that a for real code sample would be appreciated. If you really want the link for this particular question, gmail me at this nick. He got several really good answers, of which mine was at best mid-grade.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T17:31:29+00:00Added an answer on May 17, 2026 at 5:31 pm

    Your first example is strange. I’m not even sure if that would work the way the author likely intended it. The second simply wraps the first in unnecessary parens. The third makes use of a self-invoking function, though since the anonymous function creates its own scope (and possibly a closure) anyways, I’m not sure what good it does (unless the author specified additional variables within the closure – read on).

    A self-invoking function takes the pattern (function f () { /* do stuff */ }()) and is evaluated immediately, rather than when it is invoked. So something like this:

    var checkReady = (function () {
        var ready = false;
        return {
            loaded: function () { ready = true; },
            test: function () { return ready; }
        };
    }())
    $(document).ready(checkReady.loaded);
    

    creates a closure binding the object returned as checkready to the variable ready (which is hidden from everything outside the closure). This would then allow you to check whether the document has loaded (according to jQuery) by calling checkReady.test(). This is a very powerful pattern and has a lot of legitimate uses (namespacing, memoization, metaprogramming), but isn’t really necessary in your example.

    EDIT: Argh, I misunderstood your question. Didn’t realize you were calling out poor practices rather than asking for clarification on patterns. More to the point on the final form you asked about:

    (function () { /* woohoo */ }())
    (function () { /* woohoo */ })()
    function () { /* woohoo */ }()
    

    evaluate to roughly the same thing – but the first form is the least likely to have any unintended consequences.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Note: Originally this question was asked for PostgreSQL, however, the answer applies to almost
Note : The code in this question is part of deSleeper if you want
Note The question below was asked in 2008 about some code from 2003. As
Note that this has to be on a windows box as I am using
NOTE: XMLIgnore is NOT the answer! OK, so following on from my question on
Note: This was posted when I was starting out C#. With 2014 knowledge, I
(Note: This is for MySQL's SQL, not SQL Server.) I have a database column
How can I update some Windows Service Seperated Assemblies without restarting the service? Note:
NOTE: I am not set on using VI, it is just the first thing
Note that I am not asking which to choose (MVC or MVP), but rather

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.