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

  • Home
  • SEARCH
  • 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 745257
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T09:04:25+00:00 2026-05-14T09:04:25+00:00

In trying to learn JavaScript closures, I’ve confused myself a bit. From what I’ve

  • 0

In trying to learn JavaScript closures, I’ve confused myself a bit.

From what I’ve gathered over the web, a closure is…

Declaring a function within another function, and that inner function has access to its parent function’s variables, even after that parent function has returned.

Here is a small sample of script from a recent project. It allows text in a div to be scrolled up and down by buttons.

var pageScroll = (function() {

    var $page,
        $next,
        $prev,
        canScroll = true,
        textHeight,
        scrollHeight;

    var init = function() {

        $page = $('#secondary-page');

        // reset text 
        $page.scrollTop(0);

        textHeight = $page.outerHeight();

        scrollHeight = $page.attr('scrollHeight');

        if (textHeight === scrollHeight) { // not enough text to scroll

            return false;    

        };

        $page.after('<div id="page-controls"><button id="page-prev">prev</button><button id="page-next">next</button></div>');

        $next = $('#page-next');

        $prev = $('#page-prev');

        $prev.hide();

        $next.click(scrollDown);

        $prev.click(scrollUp);

    };

    var scrollDown = function() {

        if ( ! canScroll) return;

        canScroll = false;

        var scrollTop = $page.scrollTop();

        $prev.fadeIn(500);

        if (scrollTop == textHeight) { // can we scroll any lower?

            $next.fadeOut(500);

        }

        $page.animate({ scrollTop: '+=' + textHeight + 'px'}, 500, function() {

            canScroll = true;

        });    

    };

    var scrollUp = function() {

        $next.fadeIn(500);

        $prev.fadeOut(500);

        $page.animate({ scrollTop: 0}, 500);    


    };

    $(document).ready(init);

}());

Does this example use closures? I know it has functions within functions, but is there a case where the outer variables being preserved is being used?

Am I using them without knowing it?

Thanks

Update

Would this make a closure if I placed this beneath the $(document).ready(init); statement?

return {
    scrollDown: scrollDown
};

Could it then be, if I wanted to make the text scroll down from anywhere else in JavaScript, I could do

pageScroll.scrollDown();

Another Update

Wow, looks like that worked! Here is the code on JSbin. Note the page scroller doesn’t exactly work in this example (it doesn’t seem to go to the bottom of the text), but that’s OK 🙂 Bonus points for anyone that can tell me why it’s not scrolling to the bottom.

  • 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-14T09:04:25+00:00Added an answer on May 14, 2026 at 9:04 am

    Any time you define a function, that function will “enclose” the scope chain it was defined in. When that function is executed that scope chain is available in its body. When a function is defined inside another function, the scope chain includes:

    • The parent function’s locally defined variables
    • The parent function’s arguments
    • The parent function’s parent function’s local vars and arguments, etc..
    • Global variables

    The real value of closures is to return an inner function that has captured an enclosed variable that isn’t going to change, like so:

            function test (value){
                return function(){
                    alert(value); //using enclosed argument
                }
            }
    
            var t1 = test("first");
            var t2 = test("second");
            t1();//alerts "first"
            t2();//alerts "second"
    

    One danger of closures is that they enclose a reference to the enclosed properties, not a snapshot of their values, so watch out for creating an enclosing function inside of a loop like so:

    function makeArray (){
        var result=[]
        for (var i =0; i < 3; ++i){
            result.push(function(){
                alert("function #" +i); //using enclosed i
            })
        }
        return result;
    }
    
    var fnArray =makeArray();
    fnArray[0]();//alerts "function #3"
    fnArray[1]();//alerts "function #3"
    fnArray[2]();//alerts "function #3"
    

    In a loop you need to find a way to make your enclosed variables unchanging. Here is an example of using a nested closure to copy the re-used counter to a single-use argument:

    function makeArray (){
        var result=[]
        var wrapFunction=function (counter){
            return  function(){
                alert("function #" +counter); //using enclosed counter
            }
        }
        for (var i =0; i < 3; ++i){
            result.push(wrapFunction(i))
        }
        return result;
    }
    
    var fnArray =makeArray();
    fnArray[0]();//alerts "function #0"
    fnArray[1]();//alerts "function #1"
    fnArray[2]();//alerts "function #2"
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 358k
  • Answers 358k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I'd check out paper trail which will handle all the… May 14, 2026 at 2:11 pm
  • Editorial Team
    Editorial Team added an answer Try to move the <script> block after the <div id="dl"></div>.… May 14, 2026 at 2:11 pm
  • Editorial Team
    Editorial Team added an answer If you are new to Maven, I'd still suggest to… May 14, 2026 at 2:11 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.