DEV Community

Adam Moore
Adam Moore

Posted on

Iteration in JavaScript-Array.forEach() & Object for...in

Intro

Its early in the morning, you're in some week during the beginning of your coding boot-camp journey--learning JavaScript of course-- and you have a coding challenge that day. cue background scream!
Scream(Ghost-face) in the background

^^^Okay definitely not that kind, but you get my point.

Of course you may feel prepared with what you've learned about the language so far; so you give it your best shot "....deliverable 1...check....deliverable 2....uh oh..." That 'uh oh" moment happened to me on the first code challenge of my software engineering education. Deliverable 2 had many requests to rendered data to the web-page, all of which relied on the JavaScript method of iteration. I of course blanked, spending well over half the allotted time with 'null' to show for it. <=See what I did there?
Pete Davidson Chuckle

Anyway, to put it simply: iteration allows the developer to move through elements of an array or an object's properties/values they may need in order to render content onto a web-page.

You might be asking: "What is an Array or Object?"

image

An Array is a data structure that can be linked to a variable and used to store different elements, the elements are stored within square brackets => []. each element within an array has an index number, beginning with 0, and those elements can be accessed via [] notation. EX: console.log(myArray[0]) would log '//=>1 ' to the console.

image

An Object, on the other hand, is a data structure that is standalone, although can be assigned to a variable, and has properties(keys)/values. Object's properties(keys)/values are stored within curly braces => {}. These key/value pairs can be accessed with Bracket notation [], or Dot notation '.' Ex: console.log(myObject.key1) would log '//=>hello ' to the console as its accessing the value using Dot notation. All examples from here will utilize Dot notation. #writers_picks_the_preference

Supernatural epic line

=>#Secret_Tip = Arrays are classified as Objects.

Not to delve too deeply into the technicality of each data-type and their many(MANY) uses, for this post all we need to know is whether you have an array of objects, or a large object containing many key/value pairs, iterating through the nested levels or stretch pairs is essential to accessing the data you need for the deliverables that may be required of you in your career --or schooling.

.forEach()

image

For this example lets assume you have a basic understanding of GET requests from an API or local JSON file using fetch(); you have converted all of data into a response that you can use inside your Example() function, and it just so happens that the data is a large array containing objects. Example() is being used as a callback function, the parameter of the function can be named whatever you like --in this case parameter -- as you are already passing the data off as this 'parameter' within the fetch().then().then() request. Keeping the name of the parameter as the name of the data being passed through, you now have to utilize the .forEach() method inside the function to access the objects within the large array.
.forEach() only gives the developer access to the elements (Objects in this case) but not what those elements actually contain---just their face-value if you will, the 'element' within the .forEach() is used much like the parameter in this case as it represents each individual object within the array.

=>#Notes = .forEach() doesn't inherently return anything, it requires a callback to be passed through it.

From the 'element' we can pass a call back function (I prefer this to be written as an arrow function, but use what you feel comfortable with). The function we're passing is declaring a variable that finds a container within our HTML document using its #id., then its declaring another variable to be equal to a created HTML 'tag'(element); from there it gets pretty cool: the '.textContent' of that variable is then set to the element.property (Object.Key) which in turn will set the '.textContent' to that particular value. Okay, that may not seem very cool when typed out, but the kicker is that it does this for EACH of the objects within the array. <=no still not funny?
Luciefer 'tough crowd'

So, basically, if you have an array containing say 1000 objects with text or numbers as values to a key inside the object and you wanted every value to be placed inside 'variable1' ....6-8 lines of code can perform that task for you!

=>#Work_smarter_not harder

for...in

image
In the previous example we assumed you were utilizing a GET request with fetch() and implementing the .forEach() within your callback function. This example is going to be done using only a JavaScript and HTML file and the console. As you can see we have declared a variable of 'myObject' and set it equal to an object with keys of "key1: and key2" and corresponding values of "hello and bye." This object is going to be our 'data' that we will pass through the function exampleFunction(). Within this function we have a form of object iteration called, you guessed it, for...in.
The structure or this method can be broken down as:

for(variable declaration - key value iterator - in -the object)

from that method we are creating an 'h1' element set to the variable of 'variable2' and setting the '.textContent' of that variable to the values of each key in the 'myObject.' the 'console.log' within the function will log a separate 'hello' and 'bye' to the console. As you can see I may have lied about only using Dot notation during this post, as this particular example required Bracket notation to access key1's and key2's values.

Jack Sparrow lied

This method allows us as developers to access an object's key's values and implement them onto our webpage. Useful if we need to have the values of all the keys in that particular order, and all of them rendered to the page, but definitely not the best or most efficient way to iterate objects. There are many different methods that can interact with Arrays and object, perhaps a more indepth topic for another time. Thank you for reading, and wish me luck on the code challenge retake!

Best, Adam

“Continuous learning is the minimum requirement for success in any field.” - B. Tracy

Resources

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

https://www.w3schools.com/js/js_objects.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Top comments (0)