1
$grid.find( 'div.bb-bookblock' ).each( function( i ) 
{                               
    var $bookBlock = $(this),
        $nav = $bookBlock.next(),
        $navNext = $nav.find('.bb-nav-next'),
        $navPrev = $nav.find('.bb-nav-prev'),
        $navFirst = $nav.find('.bb-nav-first'),
        $navLast = $nav.find('.bb-nav-last'),
        $playStop =  $nav.find('.bb-nav-play-stop'),
        isPlaying = false,
        autoplayTimer = null,
        bb = $bookBlock.bookblock( 
        {
            speed : 600,
            shadows : false
        });

});

will all the variables inside the .each function have scope only inside the loop? For example autoPlayTimer will be the result of setInterval. I want to make sure I am not overwriting variables. It seems it is working ok, but I want to make sure I understand $().each

2 Answers 2

4

Variables in Javascript have functional scope.

So all the variables declared inside locally will only be available in the scope of $.each because of the callback that is a function.

$grid.find('div.bb-bookblock').each(function (i) {
    var $bookBlock = $(this),
        $nav = $bookBlock.next(),
        autoplayTimer = null;

    bb = $bookBlock.bookblock({
        speed: 600,
        shadows: false
    });
    console.log($bookblock) // logs the current jQuery object in iteration
    console.log($nav) // logs the next element
    console.log(autoplayTimer) // null or the value if available
});

console.log($bookblock) // undefined
console.log($nav) // undefined
console.log(autoplayTimer) // undefined
Sign up to request clarification or add additional context in comments.

Comments

2

Variables defined in functions are always in scope of this function only. This is not a matter of each() but of the function(i) {...}.

Comments

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.