Press "Enter" to skip to content

ES6 Tutorial – #7 Iterating Objects & Arrays


hey guys alex is back here with another
episode so in this tutorial I’d like to
talk about iterators and specifically
the new for of iterator in es6 but
before we dive into that I want to first
go over the different ways to iterate
through objects and arrays in JavaScript
so let’s begin with objects let’s say we
have a function that’s going to be a
function constructor and we want to
create a blueprint for a car object or
car class and let’s say a car might have
a make and might have a model and I
might have a year right so basically
we’re just gonna assign all of them to
the local or internal properties like so
and last through the year and this year
equals a year yeah and then let’s create
an instance of the car class car equals
new car and maybe the make would be
Toyota I’m not really into cars but
let’s say Camry maybe 2017 okay so what
are the different ways to look through
the object properties well one of them
is for in and for in loop basically it
does exactly that it allows you to
enumerate over object properties so the
way you would do that is we you would
basically have four and you might have
your variable you could either use var
you could use let’s I’m gonna use let’s
just because of scoping because we don’t
want to expose the properties outside of
the loop so might have like drop in car
let’s do console.log prop and of course
that’s gonna give us the three
properties make model and year now let’s
see wanted to extend the car prototype
let’s say we wanted to add a method on
it we might do something like car
prototype it let’s add a drive function
or drive method maybe it accepts the
speed by which the car is gonna go so in
this case he might actually add a new
property let’s say speed and let’s
initialize it to zero by default and
once you call that function it’s
basically going to assign the new speed
value like so
now what do you think is going to happen
right now if you look at the output
right there not only do we get the make
model year and speed like the four
properties that we define in the
constructor function but we also get the
drive method now in order to understand
why this happens you need to first
remember that every single object in
Java step has a prototype property but
basically the prototype holds a
reference to the parent object of that
object and this is basically how
inheritance works in JavaScript like we
talked about classes in one of the
previous episodes I mentioned that
JavaScript does not have a class-based
inheritance like other languages namely
you know Java c-sharp Ruby PHP whatnot
so those languages implement inheritance
with classes JavaScript enrollments
inheritance with prototypes so
productize basically allow you to
inherit properties of parent objects so
when you use the for in loop one of the
caveats of that loop is that basically
loops through all the properties on the
entire prototype chain so let’s say if
we have a car object right there not
only is the loop going to iterate over
the four properties that we define in
the constructor function so that the
direct properties or the properties that
the object itself owns so in this case
the car owns the make model year and
speed but the for loop it’s also going
to access the drive function on the
prototype because the loop is going to
basically iterate through all the
properties including the ones in the
prototype chain so if you wanted to
avoid the situation and not have the
drive function be included so if you
basically wanted to iterate over the
object’s old properties use a special
has old property method so you could do
if car has own property and then you
pass that property in there and then you
indent it and the output right there as
you can see it’s basically going to give
you the object’s own properties the cars
own properties excluding any of the
properties that are defined on the
prototype so this is a standard way to
iterate over objects but there’s a few
more than we want to look at so another
to iterate over objects in es5 actually
so this so far has nothing to do with
es6 I’m just wanna go over the different
ways to iterate objects and arrays so
one of the other ways to iterate objects
would be to combine the use of object
keys method as well as the array for
each method and we’re gonna look at for
each later in this video but for now
let’s say we do object keys we’re gonna
pass the car object basically if you
wanted to console.log that out let’s do
that first
just to see what the output is gonna be
that’s gonna give us an array with four
properties make model year and speed now
notice it doesn’t give us the drive
property that’s the fun in the prototype
and that’s a expected behavior of object
keys method basically that method allows
you to get access to the objects own
properties excluding any properties that
are defined in the prototype chain in
this scenario we don’t need to use the
has own property and that’s one of the
advantages so if you combine that with
the for each method because the result
of this call would be an array so you
could chain that but if for each method
you can pass a callback function and the
very first argument would basically be
the property or the key all right
you could call it a key and then let’s
do console log of that key all right
that’s gonna give us all the four
properties as we expect
now of course any assets you can
simplify this a little bit you can
remove the function keyword you can
remove the parentheses because you only
have one argument when you put the arrow
you can also remove the toilet races
like so we can bring all of us in on
just one line like so and it’s gonna
give us the exact same result as before
now one of the cool things about the for
each function is that it not only allows
you to iterate over elements of the
array it also allows you to get access
to things like the index so the element
as well as the array itself so in this
case we’re looping through the keys all
right you might just call it key let’s
bring back the body of the function just
to make it more readable let’s the
console.log
key and that’s and the keys and let’s
see what that gives us well it’s gonna
give us the four properties as you
expect but it’s also gonna give us the
index so from zero to three and it’s
gonna give us the array itself so this
is the array that the object keys method
returns this is the array that we apply
the for each method on so that’s another
way to iterate over object properties
it’s a little bit inefficient and that
it’s actually slower than the for in
approach and the for in loop even to
this day remains one of the fastest and
one of the simplest ways to iterate over
objects now in es6 we’ll get introduced
to the new for of syntax and the new for
off syntax it basically allows you to
loop through iterable objects and those
iterable objects include objects like
arrays string but also the new map and
set objects that we’re gonna cover on
later in this series now the important
thing to keep in mind is like I
mentioned the for off syntax it will it
only works for iterable objects so if
you try to do let’s say for let prop of
a car that’s not going to work and if we
tried console.log prop you open up the
console log the dev tools in chrome
you’re gonna see that it gives us the
uncaught type error that car is not
interval the message is going to look
different if you were actually gonna
apply the babel processor as you see
right there so it’s gonna give us a
little bit different message but
basically the essence is that you cannot
iterate over simple objects like we have
one here what you can actually do is you
could call the object keys on the car
object so this is gonna give us an array
and now we’re basically iterating
through all the elements of that array
and it’s gonna give us the same four
properties as before and notice in this
case the advantage is that we are not
iterating over the drive method right so
the drive method is excluded from the
results of the method call the result of
the keys call and the object class and
that’s because the keys method returns
only
the object’s own properties meaning it
excludes the ones that are defined on
the prototype now of course if you
wanted to iterate over the values of
those properties you could call object
values method and essentially that’s
gonna give you all the values that those
four properties hold now when it comes
to other approaches of iterating objects
different libraries might have different
ways to achieve this result so let’s say
in jQuery there’s a and each function
where you basically pass the object and
then you pass the callback function
which is going to have a key and a value
so this is how you would basically
iterate over an object and jQuery of
course it’s a little bit slower than
using the traditional for in loop
because in this case you’re making a
function call it’s gonna take a little
bit longer in underscore there’s a for
each method and there’s also the
Aaliyah’s each method and you could use
those arrays as well as objects and
let’s same lodash there’s also a for
each there’s an each alias but besides
there’s also a for in and there’s even
for own which basically adds as a
foreign loop with the has own property
check inside of it so you don’t have to
implement that logic yourself so this is
pretty much it for iterating objects
what about iterating arrays well let’s
say we have an array of cities so we
might have let’s say Chicago New York
oops
to New York that’s a Los Angeles that’s
a San Francisco and maybe Houston ok so
let’s say we wanted to iterate over the
elements of that array well one of the
first things that you might reach out
for is the for in loop and it does have
its own advantages and disadvantages but
as you’re gonna see it’s actually not
designed for iterating over arrays so
let’s say we had 4 left index in cities
and we do a console.log index and we do
console.log cities index
like so well the reason this works is
that arrays are also objects right so
every single element that we have in the
array well it’s basically assigned to an
index because arrays are essentially
ordered collections of values so every
single values assigned to an index in
this case Chicago would be at index 0 so
that’s 0 it basically becomes the
property so you have something like 0
that’s the property it’s assigned the
value of Chicago then you have one
that’s assigned the value of NewYork and
so on so the way this works is you
basically use the loop to iterate
through the properties or indices in the
array and then you can access the value
of those properties when you apply the
index on the array and this used to work
but the thing you need to keep in mind
is that the for in loop the traditional
book that we use for iterating objects
well it’s actually designed to enumerate
object properties and it’s not really
meant to be used when you want to
iterate over array like objects so it’s
really best to avoid using the for in
loop when you iterate over arrays
because first of all the order of
iteration is not guaranteed meaning that
the array indices may not necessarily be
visited in sequential order but the
other reason is that the inherited
properties will also be enumerated and
we saw this with objects in the previous
example a couple of minutes before but
basically when you’re dealing with
arrays don’t forget that those are also
objects so if you use the for loop well
it can actually bite you if you extend
the array prototype if you try to
include a custom method there this is
actually something that might come up in
older code bases but basically age also
does not prevent you from expanding the
internal or built-in objects and their
product types so you might do something
like array prototype and then you might
define a custom method on that product
type so let’s say really it’s something
that you shouldn’t do but in this
example let’s do a simple silly example
here so what’s the sine of function to
all right so let’s say what did that and
you could already see in the output that
when we use the for loop not only do we
get the elements of the array but we
also get the custom method that we
defined in the array prototype and this
is something that you would expect right
because we saw this behavior with
objects whenever you define a custom
whenever you define a method on the
prototype that method is also going to
be listed when you enumerate through the
properties using the for loop and that’s
not above that’s basically how the
foreign loop works like I said before
multiple times the foreign loop doesn’t
only go through the objects or
properties it also goes through the
entire prototype chain so it’s also
going to touch on the properties that
are defined on the prototype of that
object now this leads us to the
philosophy that you should never really
modify objects and that you don’t own so
doing something like this is really not
advisable I would really advise you not
to do this ever but you can run into the
same problem if you use some kind of a
library that does actually rely on
extending native prototypes and that
might be the case especially for older
libraries but for now just keep in mind
that using the for loop is not the best
idea when you’re working with arrays so
what are some of the alternatives when
you want to iterate over arrays one of
the alternatives to the for in loop is
to use the traditional for loop so let’s
say we had in index here I sent to zero
because you want to begin typically you
begin with a zeros index then you
basically have a check that says index
is less than city’s length and makes it
the built in property of any array in
JavaScript and then you increment the
index like so and then you have your
body of the loop and you could do
console.log cities index and of course
that’s gonna give you the five cities of
you expect now one of the other things
that you might want to do is you might
want to cache the length here so you
might define a second variable that’s
going to hold the value of CDs
and then instead of accessing the length
of every single iteration you might just
put the length in there so these two
variables are going to be scoped to the
body of the loop they’re not going to be
accessible outside and this length is
going to be cached for the you know axis
at multiple times through every single
iteration now in reality the advantage
of this caching is actually quite
negligible if you’re on you know real
actual tests you’re gonna see that the
difference is very tiny and that’s
because the body of the loop takes a lot
more processing power than doing the
comparison condition right there and in
fact modern GS engines you know modern
browsers will actually automatically
perform this optimization for you
you know given that you reach a certain
amount of iterations in your loop so you
might say that this trick right there
that we did it’s sort of like a
premature micro optimization that really
doesn’t make that much difference when
you actually run your code and the other
disadvantage or the inherent quality of
this for loop is that it’s imperative
then we’re gonna come back to this idea
later but basically we’re talking about
imperative and declarative programming
in this case the for loop is imperative
because we’re basically describing how
we want to iterate over the array here
we’re basically explicitly saying okay
you first have to define the index then
you want to check that that index is
less than the length of the array on
every single iteration and once you
finish iterating every single time you
want to increment that index
so we’re basically describing or we’re
basically laying off every single step
for JavaScript and how we want to
process this right instead of just
processing it so this approach is known
as imperative and this is in contrast to
the declarative approach which we’re
gonna see in a few seconds the other way
to iterate over a race will be to use
the for each method so every single
array has a for each method that’s been
added in es5 and it basically allows you
to pass a callback function so you can
have your city in the anonymous function
and you can just simply do console.log
that city so the for each method is
basically gonna go over every single
element in the array
and it’s gonna pass that element to the
callback function that you provide so in
this case we’re going to access the city
so compare this through the previous
example where we had the for loop we had
to access the element of the array using
cities and the brackets and then the
index
now in this case you can access the city
directly so that’s one of the advantages
of course in es6 we can also simplify
this we could use the arrow function we
don’t need the curly braces right there
so we can remove them completely and we
can put all of this into one line like
so and it’s gonna give us the exact same
result and the other thing that
convention before you’re not limited to
just the array elements but you could
also have access to the index in case
you need to access it and you can also
have access to the array itself so you
might have your cities so let’s
console.log out
city the index and the cities themselves
now the other thing is don’t forget that
this function is an anonymous function
it’s a callback function so the cities
vary more right there it’s actually
being scoped to this function so it
doesn’t conflict with the cities
variable outside and it executes without
any errors so as you can see we get the
cities we also get the index and we also
get the array of cities as the third
element in the output now the other
thing to note about this approach is
that it’s declarative now going back to
the imperative and declarative paradigms
and programming when you’re dealing with
a declarative approach
it’s basically concerned with what we
want the result to be so the declarative
approach is opposed to an imperative
approach it focuses on what the outcome
needs to be rather than how it needs to
be achieved so notice in this case we’re
not telling JavaScript how we want to
iterate over the elements of the array
we’re just saying okay just iterate over
the elements I don’t care how you do it
I just want to have access to every
single element and I want to have my
index and what I have my original array
of course those are optional you can
remove them but in this case the
important thing is that we’re not
explicitly defining how the iteration
needs to be implemented and on the same
note the for each method it actually
contains the imperative abstraction
built into it so the for each method
itself deals with iteration and
so that we don’t have to concern
ourselves with how that needs to be
implemented we’re achieved and then
lastly there’s also in es5 the map
function so the map function that
basically iterates over the elements of
an array and it invokes a callback
function or every single element of that
array so in the end the result of the
call to the map function is gonna give
you a brand new array with the elements
that you apply your callback or
processing on to so just to show how
this works we’re gonna have our cities
to call the map function right that’s
the callback to it you might have your
city and then you could basically do
console.log the city now this is not
exactly the way that the map function is
supposed to be used in fact if you do
let new cities and you try to
console.log that out after the map
function has been executed that’s gonna
give you an array of undefined well like
I said this is not really the way that
the map function is supposed to be used
the way it’s supposed to be used is you
are basically returning a new element
for every single element that you
iterate over so in this case the map
function is meant to be used with the
return keyword you can return the city
right like so but it makes more sense to
modify the city string right there so we
might do something like let’s do
something silly let’s say I love and
then the city
alright so that’s gonna give us the
output right there okay the other thing
is we could also use string
interpolation so we could use the batiks
and he is 6 so we could do something
like this once a week but the closing
quote right there and then we put the
dollar sign and the curly braces around
it like so so the city is going to be
injected into the string and of course
the other thing we could do is we could
also use the arrow functions like so we
can remove the be curly braces all right
and the return keyword would be implicit
so what I actually need it put on the
same line and we get this
it’s gonna give us the exact same output
as before so like I said before in this
case the map function it’s going to
execute a callback for every single
element in that array it’s gonna apply
that logic for those elements and it’s
gonna return a brand new array that
contains two new modified elements in
there so as before
besides the city you could also have
access to your index and even oh so
sorry you can have access to the index
and you can also have access to your
city’s array now as I mentioned before
if you just want to console.log out your
city like so all right
in this case it doesn’t really make much
sense to use the map function because
it’s not what it’s meant to be used for
semantically it makes a lot more sense
to use the for each method right because
in this case we just want to iterate
over the elements and want to
console.log out the city this case we
don’t even need access to the index or
the city’s array so we just remove those
and the other console.log doesn’t make
any sense so we can kill it so this just
gives us access to all the cities and if
your objective is just to simply iterate
over the elements of the array for each
is perfectly fine if you want to get a
new array if you want to process the
elements of the array maybe you know
apply some kind of a logic to them or
modify them in any shape or form then
using map makes more sense for that now
the very last approach you want us to
look at is the for of iterator or the
for of loop and this is basically the
reason why we’re doing this video it’s
the new for ops index that’s been added
in es6 and the way it looks is something
like this so you might have your for
loop with the city of Cities now notice
the new off keyword this is not d in as
you would use for objects this is the
floor off like so and just simply do
console.log city means you would expect
this is gonna give us the five elements
of the array now so far this is the most
elegant approach because we don’t have
the boilerplate code like we typically
would when let’s say a traditional for
loop where I have to define the indexes
and all the other variables they have
nothing to do with the objective of our
code but in this case you need to
remember that if you use it before
loop it makes sense to use it as long as
you don’t need to have access to the
index of the elements right because in
this case we just get the element itself
and the other caveat is that the four of
loop is not natively supported on older
browsers like let’s say Internet
Explorer so if you need to support the
older browsers you need to make sure
that you use polyfills or you can also
use the babel preprocessor the Babel
library in fact if your objective is to
be as cross browser compatible as
possible and you could just use the
traditional for loop because it goes way
back to Internet Explorer six or
something like that now when it comes to
other approaches when working with
arrays of course you can use the
traditional while loop you could also
use the reversed for loop or the reverse
while loop and the way those work is
that you basically start at the index of
length minus someone and you work your
way backwards to zero
so you’re sort of like going from the
last element of the array to the first
one that sort of makes sense when the
order of elements is relevant now the
other thing you can also do is you can
use the filter method on the array and
it basically allows you to get a
brand-new array with the elements that
pass a given test and your test would
basically be inside of your callback
function right you could also use the
new es6 syntax with the arrow functions
like so the other approach you might
take is you might use this sum function
on your array and the self function it
basically checks whether at least one
element of the array passes a given test
lastly you could also use the every
function if it does make sense in your
case in your scenario if that function
essentially allows you to check whether
all of the elements of the array pass a
given test and again the test would be
inside of your callback function right
and the very last thing I want to
mention is if you’re dealing with
utility libraries like jQuery lodash
underscore already mentioned those they
do have their own built-in methods
typically it’s each or for each there
might be some other implementations and
library is even like angular being
have their own implementation of the for
each iterator now that’s about it for
this lesson thanks a lot for checking
out my channel and I’m gonna see you in the next episode

Please follow and like us: