Search code examples
javascriptiife

Understanding IIFE


in my page i have several img tags as follow:

<img class="img-fluid meeseks" src="img/meeseks_red.jpg" data-color="#ee5b61" />

in the js file i've created this:

function Store(path,color){
    this.path=path
    this.color=color}

and then, starting writing the code, i wrote this:

img_path=[]
    for (var i=0;i<img.length;i++){
        img_path.push( new Store(img[i].getAttribute("src"),img[i].getAttribute("data-color")))
    }

to obtain an array of object that stores the src and color of every image.

Now, studying the IIFE, i wrote this that also seems works:

(function store_inf(){
    img_path=[]
    for (var i=0;i<img.length;i++){
        img_path.push( new Store(img[i].getAttribute("src"),img[i].getAttribute("data-color")))
    }
    return img_path

})()

Which way is better in this case? I also noticed that if i omitted return things works normally (i always have an array of object if i log the img_path arrays)

So the IIFE return an array that is permanent, even after IIFE has been invoked, in the global scope? thanks


Solution

  • Your current code works because img_path is actually global and your IIFE is useless. You may do:

    var img_path=(function(){
    var img=document.getElementByTagName("img");
    var img_path=[];//now local
    for (var i=0;i<img.length;i++){
        img_path.push( new Store(img[i].getAttribute("src"),img[i].getAttribute("data-color")))
    }
    return img_path
    })()
    

    Now theres an enclosed img_path and img array and a global img_path.

    Note that you could also do:

    var img_path=document.querySelectorAll("img").values().map(el=>new Store(el.src,el.getAttribute("data-color")));