Question about forEach

offsite
javascript

#1

Hello everyone,

I was reading the JS Objects in Detail article over at javascriptissexy, and about one-third down, it says:

If you have done the Learn JavaScript Properly course, you would have seen the lessons in the Code Academy used this first pattern frequently: [code is below]

This program utilizes forEach. The first time I saw this page I hadn't done all the exercises, but now I'm done with the track and I don't remember using it.

Looking at the program I can sort of understand how it works, and I tried to read MDN's forEach page but am still confused.

Can someone please explain what forEach does in an easy-to-understand way?

Thank you,
frisby

Note: just to be clear, this post is not a complaint about forEach "missing" in the lessons. I understand Codecademy and JiSS are separate entities. Seeing it referenced as something I should know simply instigated in me a desire to know.


function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) {
​
    this.color = theColor;
    this.sweetness = theSweetness;
    this.fruitName = theFruitName;
    this.nativeToLand = theNativeToLand;
​
    this.showName = function () {
        console.log("This is a " + this.fruitName);
    }
​
    this.nativeTo = function () {
    this.nativeToLand.forEach(function (eachCountry)  {
       console.log("Grown in:" + eachCountry);
        });
    }
​
​
}


20. Penguins, Properties, and the Prototype
#2

@msfrisby,
An example ??

function Fruit(theColor, 
               theSweetness, 
               theFruitName, 
               theNativeToLand) {
    this.color = theColor;
    this.sweetness = theSweetness;
    this.fruitName = theFruitName;
    this.nativeToLand = theNativeToLand;
    this.showName = function () {
          console.log("This is a " + this.fruitName);
          };
    this.nativeTo = function () {
    this.nativeToLand.forEach(function (eachCountry,index,array)  {
       console.log("Grown in:" + eachCountry,theSweetness);
       console.log(index,array);
       //console.log(this);
        });
    };

}

var aFruit = new Fruit("color",["not","very"],"peach",["Japan","India"]);
aFruit.nativeTo();

#3

Thank you, @leonhard.wettengmx.n. So then is forEach acting like for...in but for arrays that are object properties? :worried:


#4

@msfrisby,

http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object

var myObj = {
    key1: "a",
    key2: "b",
    key3: "c"
};
myObjArray=Object.keys(myObj);
console.log(myObjArray);

#5

Ah, I see, so to do "for...in but for arrays that are object properties" I should use Object.keys; thank you, @leonhard.wettengmx.n! In that case I am still having trouble understanding what forEach does... is it "enumerating" properties for a fellow key?