the12 the12 - 1 year ago 83
Javascript Question

When are variables set in JavaScript?

I found a basic JQuery carousel online and was curious why it worked, when in my mind, depending on when the variable was processed, it maybe should not have.


<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
.carousel div {
z-index: 0;
.carousel div.previous {
z-index: 1;
.carousel div.current {
z-index: 2;

height: 50px;

<body><script src="" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>

<div class = "carousel">
<div class = "current"><img src="" alt=""></div>
<div><img src="" alt=""></div>
<div><img src="" alt=""></div>
<div><img src="" alt= ""></div>


setInterval(rotateImages, 3000);


function rotateImages(){
var currentPhoto = $('.carousel div.current');
var nextPhoto =;
if (nextPhoto.length == 0){
nextPhoto = $('.carousel div:first-of-type')
//Point A

//Point B
nextPhoto.css({ opacity: 0.0 }).addClass('current')
.animate( {opacity: 1.0}, 1000, function(){

What I mean by variable setting is when does JavaScript set the variable, in this case, the variable nextPhoto to a certain selector i.e.: the preceding div after it.

My confusion stems over the fact that if at point B JavaScript sets the selector there, then the equation would not work, because in the previous step, you have removed the element with the class "current", hence when JavaScript ties to set the variable nextPhoto, it shouldn't be able to find anything because at that point in time, there would be no element with the class current, hence no preceding element (nextPhoto =

If it is at Point A it makes sense, but I'm wondering at what point in the equation does JavaScript set the variable so that I can design equations with that in mind. If you could tell me via the code above and writing what point does JS set variables that would be great!

Answer Source

As soon as you do the first assignment:

var currentPhoto =...

currentPhoto is a point-in-time snapshot of the selector's state. Future changes to the set do nothing to change that set. Your .next() call will pull the very next item no matter what, unless you explicitly change the content of currentPhoto itself (not it's deep data).

nextPhoto will get the new classes as they are assigned, but the selector itself has already been run.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download