What is the difference between if () {} and if () in javascript

advertisements

I've written this code, which is a basic image gallery in jquery

$(document).ready(function() {
 setInterval("rotateImages()",2000)
 })

function rotateImages() {
     var curPhoto = $("#photoshow div.current");
     var nextPhoto = curPhoto.next();
     if (nextPhoto.length == 0) {
         nextPhoto = $("#photoshow div:first");
     }
     curPhoto.removeClass("current").addClass("previous");
     nextPhoto.css({
         opacity: 0.0
     }).addClass("current").animate({
         opacity: 1.0
     }, 1000‌​, function () {
         curPhoto.removeClass("previous")
     });
}

This works, except when I wrap the if statement with {} it doesn't. I just wanted to understand the difference between the two and why it wouldn't work.


multiple lines need {}, otherwise the javascript interpreter doens't know it has more things to run.

try this, it has to work:

$(document).ready(function() {
    setInterval("rotateImages()", 2000);
})

function rotateImages() {
    var curPhoto = $("#photoshow div.current")
    var nxtPhoto = curPhoto.next();

    if (nxtPhoto.length == 0) {
        nxtPhoto = $("#photoshow div:first");
        curPhoto.removeClass('current').addClass('previous');
        nxtPhoto.css({
            opacity: 0.0
        }).addClass('current').animate({
            opacity: 1.0
        }, 1000, function() {
            curPhoto.removeClass('previous');
        });
    }
}

P.S. please also use semi-colons (;) to differentiate lines.