Javascript Function Understanding

66 views Asked by At

I am currently working on javascript function but these programe make me little bit confuse kindly please explain whole about the program given below, confusing towards for loop decrement.

var socialMediaIcon = {
    facebook: "http://facebook.com/haseebjumani",
    Twitter: "http://twitter.com/haseebjumani",
    whatsapp: "http://whatsapp.com/",
    flickr: "http://flicker.com/haseebjumani"
}

var social = function() {
    var output = '<ul>',
    myList = document.querySelectorAll(".social-media");

    for (var key in arguments[0]) {
        output += '<li><a href="'+ socialMediaIcon[key] + '">' + 
        '<img src="images/' + key + '.png" alt="icon for' + key + '">' + '</a></li>';        
    }

    output += '</ul>';
   
        for(var i = myList.length - 1; i >= 0; i--){
        myList[i].innerHTML = output;
    };
    

}(socialMediaIcon);
<!DOCTYPE html>
<head>
    <title>Social Media Icons</title>
</head>
<body>
    
    <nav class="social-media">g</nav>
    <h1>Welcome</h1>
    
    <p> lorem ipsum delor sit amit lorem ipsum delor sit amit lorem ipsum delor sit amit
        lorem ipsum delor sit amit lorem ipsum delor sit amit lorem ipsum delor sit amitlorem ipsum delor sit amit
        lorem ipsum delor sit amit lorem ipsum delor sit amit lorem ipsum delor sit amit lorem ipsum delor sit amit
    </p>
    <nav class="social-media"></nav>
    <script src="social.js"></script>
</body>
</html>

1

There are 1 answers

0
xxCodexx On

The problem here is that <nav class="social-media"></nav> is used twice over here. So when you reach at this point of code for(var i = myList.length - 1; i >= 0; i--) it starts looking for myList in code which you have defined as myList = document.querySelectorAll(".social-media"); If you have a close look in your for loop initialisation you will find follwing:

for(var i = myList.length - 1; i >= 0; i--)

First Iteration:

var i = myList.length - 1 /* 1 in this case */ 

now i >= 0  sets as True 

then you will see social icons on later .social-media as index in for loop is set as 1

Second Iteration:

var i = i-- /* here value of i is set to 0 */

now i >= 0 also sets to True

then you will seel social icons on first .social-media as index in for loop is set as 0

Other method if you want to use i++

Please initialisation your for loop as :

for(var i = 0; i <myList.length; i++)