1

I've recently asked the question about the difference between the function level scope and block level scope. The answer was comprehensive and helped me to understand the function level scope and introduced the hoisting concept.

Now I have another deliberation. The example is a jQuery .ready() function and an event handler declared within it. That is to say, why a variable declared in .click() event handler is not being hoisted up to the .ready() function ? Is that because .click() is not property of the .ready() function ? and the variable declared within .click() is being hoisted only up to that function?

Example:

$(‘document’).ready(function(){
    $(‘selector’).click(function(){
        var x = 10; //discussed variable
    });
});

I'm trying to teach JS script myself, but this concept is really hard for me to understand. Could someone explain that with a simple example, or provide relevant link, please.

Thanks

1
  • 1
    FYI, use $(document) not $(‘document’) Commented Feb 16, 2014 at 18:28

1 Answer 1

4

The .click event handler is an anonymous function, and therefore like any other function has its own scope. Variables declared within it stay within that scope.

Hoisting only applies within functions - variables don't leak into the enclosing scope. If they did then function scope would be useless...

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, I think I've got it, I've got confused with the loop block or the if statement block which was used as an example in aforementioned question. Thanks.
@Dimt yes, unfortunately you were misled by one of the comments on the accepted answer to the other question - variables declared in an inner function are not accessible in the enclosing function.
However the answer was good, just I've misinterpreted it. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.