Transcripts
1. Class intro - arrays: Welcome skill, say students to yet another class. And this class is super, super exciting. If you've been following me along on my other lectures and other classes, great, if not less, telephone to. This clause is almost a standalone class. You can look at it in isolation. But of course I always recommend you go through the entire series because we've covered a lot when it comes to JavaScript. Now this is the important thing you need to understand. When it comes to programming. What is it? What do you work with as a programmer? It's just daughter when work with dots and we get different types of data. And that's why one of the previous classes, we spoke about this a lot and we discovered that in programming in JavaScript, daughter can be divided into two types. You've got basic types of data or primitive. And he's got to complex data types, aka objects, when it comes to JavaScript. And arrays fit into the complex type of daughter category. And as you'll see in the lecture, arrays are actually a type of object in JavaScript. So collide, what are arrays and why do we need them? We'll, anytime you want to store a collection of daughter, you typically use arrays. Remember we've already seen variables, but variables can only typically hold one value. Arrays can hold a collection of values. And that's extremely useful for us when building way beds. What are some examples? Well, if he had a shopping websites and people add items today, caught all those items that edit to the code, how do we install them? Vote installed in with an array. What about if you are creating the backend for an admin user? Pull all the members of your site can be stored in an array. There are many, many examples and I'm sure you can see, and it is very, very important to master. And that's what this class is all about, arrays and loops. And we not only talk about arrays, but we also look at examples. We look at what methods JavaScript gives us on arrays straight out of the box. Methods lack push, pop, slice, cetera, et cetera, within gate. A little bit more advanced, we discussed the different types of methods would get on arrays. Black mutator methods push for example, is a mutator method, radiate accessor methods. Slice for example, is an accessor method. And then we get iterator methods. And the map function is an example of an iterative method and understood category. These iterative methods, this is extremely important because this allows us to loop through race. And as I'm sure you can see when we have a collection of data becomes very important for us to loop through these arrays. What about if you're on a website and you want to sort by price or sort by date listed. You can tell how important it is for our code to look through our entire collection sought through them. This is just one example, by the way, but you can see how important it is to discuss loops. And this is also what we do in this awesome clause. We discussed loops and we discussed the traditional for loop, which most of us already know. But don't worry if you don't within discuss the for in loop. And then we discuss my opinion much bidder loop. And that is the for of loop. So really this class is full of useful information. I really can't wait. And please stick with me. Grander coffee. Gregory bull, whatever pants you up. And I'll see you in McCloskey, adios amigos.
2. What is an array?: We've come a long way. We've learned about objects and how are we starting to get more and more advanced in? You're going to have to understand arrays when you come to programming. And I like to think of an array is a variable that stores multiple values in. I want to stress the word multiple values. We're going to see shortly what I mean by multiple values. But before we do, how do we identify an array? An object can always be identified by the curly brackets, arrays of closely related to it. And you can identify an array with square brackets. And taking a step back. Remember when we were discussing data types in JavaScript, the two daughter types, these primitive, which is just a fancy word for simple things like strings, numbers, booleans, null, undefined, and even assemble. Those are all simple data types. But then we've also got the object, which is complex data types. Although everything in JavaScript is pretty much in objects for our sakes, it's always nice to break it down and go, okay, cool. We've got objects that we know. We've also got arrays and we've also got another one functions. And those are the second type of data types in JavaScript. Ok, so putting that aside and you kind of know, erase food enters a daughter type of JavaScript. But they are just a special kind of object. And I'll prove this to you. Let's have a look. An array is just an object. And remember how he said to identify an array or to create an array, you have to have square brackets. Objects are curly brackets. List find an array, let a equal open and closed square brackets. That's it. We've created moraine. And to show you that this array is actually an object, we can just go type of a the eager to an object. And remember seed an array as like a variable that can store multiple values. Well, how do we work with chunks of data? For example, let's take a very easy scenario. Let's say we've got the numbers 1357. How do we stall that? Can we just store it as a string? Well, I guess we can, we can just write it out. 1357. That's just awkward. What about if we wanted to add the numbers together? What about if we wanted to extract just the five and leave the 137? We can't really do that with strings, can we? It's awkward. Brackets, very difficult. Images show you now a quick example of working with numbers in an array. So how do we store numbers in what's the best way? Because strings are awkward. So let's define an array and let's call it numbers. For lack of a better word. And our numbers are 1357. How we've created an array called numbers. Lets it, that's how easy it is. And if we console log up numbers and we open it up, and you can really see the console telling us at the four elements in this array. We can open it up and look at that is a few things worth noting here. One is, this array has a magical length property. Where do they come from? We're going to see shortly, don't worry. Second thing worth noting is that the key value pairs here, those keys started the number 0, y. Is that all you gotta think about the word numbers that we've created the as a reference to a memory location. And if we type number numbers 0, all the debts trying to do is it's referencing a location in memory that is x elements away from the reference point. Yeah, we've seen the reference point is 0. So it's taking the very first element finds in memory. So in this way, the index, those numbers 0123, those are used as an offset. And in our example, the very first element in the array, the number one, with a key of 0. It's x elements away from its reference point, which is why when we type numbers, it should give us one because we are literally pointing to the same memory location. The data stored in. Hope it's making stains will begin to see a lot more examples of this later. Let's move on. So we've just seen arrays are data structures that taken multiple values. Arrays don't have key value pairs. They have singular pieces of data. But what's cool is that arrays are objects. So they can contain objects as well. And we've seen arrays are a special kind of object. But one difference is that arrays have a magical length property. The first value in the array is stored under the key 0. And remember, when we looked at the JavaScript object model where the ECMO scripts spec defines an object is just a reference, just a dictionary where you've got the keys and those keys point to a property attributes. Well, it's the same with arrays. Let me show you an example. So let's look at the array model. How does the engine treat an array? Where does this length property come from? Well, let's define an array that just holds one value and that value is the letter a. So we've got an array, the rays called liters. It's got two properties, a length, and it's got a key, and the key starts at 0, and they point to property attributes. The length property has a value of one, but it's innumerable and configurable properties or seek to false because this is inbuilt in JavaScript. We don't to be missing the surround and reconfiguring it. The key of 0 points to the value a and that all has the default true venues leads take our array and let's push b into it. What happens in? Well now you're going to have an extra key. You're going to have a one. That one will point to a value b. And the length and the key of 0, exactly the same things as before. I hope this is starting to become more intuitive to you. Don't worry too much. I know this is a bit theoretical because this is what the engine and this is what the arrays and objects are doing in the background. A lot of people don't understand that, but it is going to help you. So let's move on. Let me show you some more examples.
3. How do we create an array?: And just as with objects, they is not only one way to create an array, but in general, we only looked at two ways to create an array. We look at an array literal, and that's just using opening and closing square brackets. And the second way is to use an array constructor. And yes, we're going to use the new keyword Day as well. Let's have a look at a few examples. What better way to learn then? Examples? So let's start looking at the different ways to create arrays. So first let's use the array literal, and this is the easiest way to create an array. And the most simple array is a, a for array. And if we console log AR two, you can see we've got an array. How easy is that? We can also create an array with values. So let's define a variable called animals, and it's defined different values, dog, cat, and a mouse. And if we console log that to the screen shot and have to use console log in this case, I can just type animals and there we go. We've gone array with dog, cat, and mouse. And remember how we said an array is an object. And we went further by saying you can even put objects within an array. Let's show an example of that. So let's call our a here people. And remember, with an array, you have to have opening and closing square bracket. And now we want to put objects into this array. How do we define an object? That's right with curly braces? And let's just say name equals one. And let's do another one. Let's call this one John. And let's do one more and name her Cindy. And if we console people out, there we go. You can see it's an array because it's enclosed within square brackets. And it's got these objects within it. Ok, that is array literal. Let's now see array constructor. And with the array constructor, you have to use JavaScript's built in array object and you have to call it with the new keyword. Let me show you what I mean. So lets define house and use the constructor editor. Now you just need to put in the values in this constructor. Call it a three-bedroom, colours red, and it's got three bathrooms. If we console this out, we should see an array with opinion closing square brackets with these venues within it. He got days house and needs the opening, closing square brackets and then the values in it, just as we would expect. But using the array constructor can cause weird results. Let me show you an example. If you wanted to do an array of numbers, it's pretty straightforward. And the array indices have numbers 510. And if we console log this out, I would expect to see an array with values 510. You've got it. And we do see that in this instance. But if we just wanted it to have an array with one number that causes weird results. Have a look at this. So let's say we've got a new array called figures, and we just want that to be the number seven. If we console log that up, what would you expect to see? Lot expect to see in array with just the number seven. But in this case it's actually going to give us something different. It's gonna give us an empty array with seven empty blank spots. I mean, figures. And the head is, hasn't given us what we expected. So for me, I just tend to use the array literal approach. It's very intuitive, very easy. Like I said, there's never one right way to do something in JavaScript. There's so many different things you can do. And depending on your situation, you may want to use one or the other.
4. Array example: The best thing is with these things is to just keep going with examples because then you start feeling more intuitive around it and you start coming more comfortable around this concept of arrays. So let's get into it. Let me give you a practical example. Let's say we've got a shopping list and we want to add to it, we want to delete things from the array. We want to access a linked properties. How would we go about doing all these things? Let's have a look. Well, the first thing is let's create a ShoppingList. And in cooler water, what you want, let's just call it shopping list. And let's just do necessities. Mlk bred via. If we console log this out. Let me start Walker. You got our array is the multivariate b-a. What about if we wanted to access properties in array? Well, we can access those properties with square brackets. And initially say we wanted to access MLK. Let's console log ShoppingList. Open, close square brackets. And remember, we've gotta excesses in memory. And it's going to be at the starting point, which is 0. And that gives us MLK. If we wanted to access via, what would we do? This, right? We put two that will give us b-a. And with arrays, we can also override values very easily. Leads over i values. That's X is our ShoppingList. Instead of MLK, it's by Kirk. Now if we console logo array that's replaced MLK Woodcock. And what about accessing the length property? What about if we wanted to add elements into this array? If we suddenly remembered, hey, I also need to buy toilet paper. Or what about if we don't want to buy beer anymore and wanted to get rid of that. How would we go about doing that? Well, let me show you some equity. Let me just open the console and look at this in irradiate recreate. Let's just creates the number array. Okay, it can be an empty array. If we console log this out and we open up this little thing here, and we exits prototype. You told us you could put we have existence. We've got access to the pop method and the push method. And let me give you examples of what goes on. Now, let's go back to our IDE. Let's axis the length property. How do we do this? Well, you'll see if we go back to the console, you'll see here that we've actually got a length property would have medically on this array, on any array we create. We've got that property directly. So if we go back to our IDE, we can access it, elicits console log, shopping-list, and its access the linked products. Three, we've got three items in RA, It makes sense. Milk, bread, and beer. Mona's case, Coke, bread and beer. Let's now add an item to our ShoppingList. How would we do that? Well, arrays have an in-built method called push in JavaScript, and it literally pushes an item onto the array. Let's xis are a shopping list. It's going to have a push method on it. And you can see my IDE already tells me that the subpoena is a new element to array, and it returns a new length of the array. So let's push toilet paper onto our array. Now if we console of this art shopping-list, and there you have it again. But now say we made a mistake and we've got enough toilet paper, we want that thing out today. What do we do now? Let's weigh cup comes into it up. Let's remove an item from the array. Again. Let's exit our ShoppingList. Now we want to pop. In this pop method wastes, removes the last element of the array, which in our case is the toilet paper. And now if we console log our ShoppingList out, toilet paper is nowhere to be seen. Great, I hope you're having fun that this mortar arrays in this, let's get into it.
5. Intro to mutator iterator: Remember how when we create an array, it automatically came with a whole lot of properties and methods attached it automatically. Remember we had the pop and we had to push and we had the length. Well, let me just say that array methods can be grouped into three broad categories. And it's very important for you to distinguish between it. Otherwise, you might mess up your code and your daughter. So the three broad categories or mutator, accessor and iterators, mutator methods or those that mutate will alter the original array. So be very careful when working with mutator methods, because what you do on that array will affect the original array. You've got access emitted, and they don't alter the array, doesn't mutate the original array at only creates a copy. And then you can work with that copy and extract and do with that copy as you please. And then finally you've got iterators. So a lot of the time with dot, actually wanting to loop through that dot, are you wanting to extract certain values and display it to the user? That's where iterators come into the picture. Let's look at examples of all three of these types of methods quickly.
6. Mutator iterator examples: We have three broad categories of methods on arrays. Let's have a look at an example of each of them. So as we just did in the lecture, let's look at mutate methods. And remember these methods alter the original array. So let's create an array delicious cold numbers for lack of a better word. And let's have 51015 in that array. And let's use the push method. The push method is a mutating method and it's pushed the number 20 on us. It's console log numbers, push. And it says here in my IDE is really giving me acuities that returns the new length of the array. And it's pushed the number 20 on to this. Now the array is going to have length four. So not console log odd numbers. It's going to have four numbers now it has affected the actual original array. Lot. Another example, let's work with colors. Let's say original colors of blue and green. But let's say someone else comes along and wants to create a minute colors, but they want to start off with these colors as like the base point. Sir, let's say mean that comes along. And they want to use the original starting point, but they want to push another colony, RED. Now when a console log original, unexpected only see blue and green. And I'm sure as you guessed it, when a lager dots actually has now read. So with this mutation, with this push method does affect the original rate. Just be careful with it because you might miss up original data that you weren't intending to do. Another method is xy submitted. Let's have a look at that now. Quickie, just copy this appeal. Would have to type it out again. And being lazy and malicious callers, accessor and exits emitters are nice because it allows us not to manipulate the original array, which create a copy of the original array and then manipulate that crackle. So have a look. Yeah, let's define an array of names. And it says John, ALI. And Cindy. Now one, X is a method available to us as known as slice. And slice just returns a specified portion of the array. I'll show you what I mean now. So let's just say copy equals names. That's our original array. We want to access a slice method. And you can see my IDs already telling us what the two arguments are. The start is the beginning of a specified portion of the array and the end which specifies when they're re, needs to end. So let's just return, say we want to return just Wally and Cindy. We didn't want to involve John in all of this. So here we can start at one and end at three. Now if we console log that out, we've got Wally and Cindy. How calls em. But I mean, if our console log up names, names has kept its original form of having three people in it. That's an accessor method. What bottom iterator method? Iterator method, as we see, it just iterates through an array and it allows you to do things with a certain value each time it iterates through that array. Cuz that's a bit of a mouthful. But again, it's much easier to understand with an example. So let's give you an example here of an iterator method. And a very popular one that you're all going to be using and probably even do a whole section on it, if not a whole section differently, one or two full-on episodes is the map method. Now there's a lot we can talk about with the men. Map methods are not gonna do it. Yeah, I'm just going to show you very briefly how it works and what an iterator method means. And let's create an array of animals. And let's just say we've got a dog and a cat. I don't wanna make it too long. And now I just want to create a iterate, an animal iterator. Let's just call it animal iterator. And we're gonna access our, our original array and we're going to use this map method. Ok. And as you can see in my IDE, this map emitted calls a callback function on each element of an array. And by element of an array we just saying the dog and the cat in this case, those are called elements. So a function is going to be called returning a dog and returning a cat, et cetera, et cetera. Don't worry about callback functions yet we're gonna get into these things later. So the first argument in this map method is the callback function. You can even see that MID, it's telling me. And let's define a callback function that takes the element, which in our case is an animal. It's a type of animal type. And then let's do something with that animal type. So in our case, let's just console log statement that's used template literals. And let's say, I don't know, we are dealing with a. And then you can literally take that animal and look at what's just happened. You can see the console says we're dealing with a dog, we're dealing with a cat. So that's what the map method does. It takes each element of your array. So on the first iteration, on the first loop, it's going to take dog. It's gonna put that dog into that callback function. And it's going to name that. It's gonna put that dog into a variable called animal type. And then we just do whatever we please with it. In this case, we've just done a simple console log message of that animal type. But this doesn't affect the original array. If I type animals, we've still got our dog and cat and nothing to it. It's just a method that allows us to iterate through an array. We've gone through a lot. We've gone through a lot. Well-done. Hope is starting to make scenes. See you soon.
7. Why is looping necessary: Working with daughter is extremely important when it comes to programming. And a lot of the things we've been doing at the moment had been as storing data and we'd be putting it into objects. We've been defining variables, we've been creating arrays. But what about accessing those batteries? In a, you can think if you have an application with thousands of users, they giving you daughter. But at some point you are going to want to extract that data and display it to use it to perform calculations on it. And this is we looping becomes vital. And here we're talking about looping through objects, but just bear in mind, an array is actually an object as well. You can loop through objects and you can loop through arrays. But once you have an array, a vanilla array and buy vanilla just mean you've got a whole string of values. Once you've got to that point, it becomes very easy to loop through it. So that's why I'm wanting to start with objects and more complicated object that you've defined. How do we loop through that? And you'll often find ourselves in a situation where you want to look through your object. And the only way to do so before ESX was with a for in loop. And I'll show you an example of a for in loop shortly. But let me just say there's a better way and that better ways to convert your object into an array. And then you can just loop over the array, because looping over an array is very easy now. So how can we convert our object into an array? Will they three very popular methods, object dot keys, object dot values and object dot entries. Object dot keys creates an array that contains only the property names, aka the keys of the object. Object dot values, you probably guessed already, that creates an array that contains the value of each property within the object. And object dot entries just gives you an array. But now this time you've got both the key and the value. It always creates an array of arrays. But I'll show you what this mean shortly. Okay, so let's take a step back. We start off with a complicated object within converted object into an array. And we can use one of these three methods that we've just discussed. Do that. And now we can loop through this array as if it were a normal vanilla array. And we do this with d for, of loop. The for loop is awesome and it's a much easier way to loop through elements of an array. Let me give an example. I'll just quickly show you how this for loop works. Let's say we define a whole lot of fruit keys. And it is an array that's a banana and a manga. Simple. So what does a for of loop do? That loops through each key. And what I mean by key, where your key in this case in that array, is banana. On the second iteration net key is going to be manga. For const key, it's going to take the key of the array. But now, without us doing anything, awesomeness for of loop, how does it know to use the fruit keys array? Let's wait, a second argument comes in. You have to tell this array, hey, find each key of the fruit keys array. Then you open up this for of loop with the curly braces. And we can do whatever we want with that key. Because we know on each loop that key is going to be in the first instance banana, and on the second instance manga. So in this instance, our simple console log key will just console log phenomenon the first iteration. And then on the second iteration we will console manga. Let's have a look at some more examples now.
8. Looping through an array example: Looping through daughter to extract it. It's so important when it comes to programming. And I want to really, I want to stresses. So I'm going to show you two examples. The one I'm just going to loop through arrays, show you the different methods. And then as we've discussed in the lecture, I want to actually create an object with properties, name-value pairs, and I want to loop through that. So without further ado, let's get into it. I'm going to start cutting with more complicated functions and calls and loops. Because we've come a long way. And I think you're getting really familiar with the traditional easy objects, arrays and all of that. So let's create a function. Let's say we've got a whole list of members on our side. And we want to loop through each member and give them a welcome message. How do we do that? We'll firstly, let's create a function and we're gonna get into functions in a completely whole new section. So don't worry about syntax yet. Just understand the concept. Let's define a function called High. And it said that function takes in the person's name. All this function does is it returns our welcome message. Welcome, and we using template literals, Yeah, and we're just going to cancel out the name. Next. Let's find our members. And let's say with what, a whole list. And we just starting out. So we've only got two members, Tom and Jerry. But then let's say we get new users, new uses. John and Wally. So mainly lists that's pushed John. And as to the sad and push Wally, now, a member list should contain four members. And it does. And we wanting to greets all members. How would we go about doing this? Well, remember how I keep stressing these never one right way to do something. And there's lots of ways to loop through this array. Just look at the traditional old-school ways first. So the traditional for loop, and something worth remembering is that every for-loop has curly braces at the end. And it's kinda like what we wanna do in code, goes in-between these curly braces. What differs is what's in the parentheses here. So for the traditional, so let's start off here with traditional. Old-school for loop. We have to define a variable. And that variable iterates by one each time the loop completes. So we can call this anything. But traditionally people liked cool it. I, so we say let i equal 0, so i's going to start at 0. And then the second parameter in this for loop sees under what condition will the loop continue to loop? Because eventually the loop's going to have to stop. Otherwise it's going to be an infinite loop. So let's say here, we only want this to iterate how many times? Let's write only four times because they form inverse, right? So we need i to be less than the member list link. And then the third parameter is what happens to i after the first iteration. And we want to increase by one. So when we start IS, does the first loop, when it finishes, that eye's going to be increased by one. And then this condition is going to be tasted. Habit makes it. And now I wanted to find a greeting, a particularly accreting for each member. Lets say LIT greeting. This is where we want to return high function. And remember the hi function, one of its input parameters was the name of the individual. What is the name of this individual on the first loop? Will it's going to be symbolist. And remember to access properties on array, we can use a square brackets. And here I am. On the first iteration RBF network turn the name Tom. And in all we want introduce console log. Greeting. Today you have it. We welcome Tom. Welcome Jerry. Welcome Jon. Welcome Molly, how cool is that? I hope you understand what it is we did, but again, this is an old school for-loop. I'll show you a better way to do it. But before I show you the best way to do it, let me show you another old school where it's called the for in loop is also old school way. The for in loop. Again, we have the four and then we put these curly brackets. And now all we have to do is we have to get four const name in the symbolist. This syntax is doing is on every loop it's going to get each element in our array. We've called our element name because we know their names, Tom, Jerry, John Wiley. So it's going to grab that name in our object member Ernest in our array. And then traditionally what this does is that this actually accesses all the prototypes properties as well. So I can get very cumbersome and sometimes it accesses things that shouldn't. And for this reason, you often include an if statement within this for loop. And you just have to say if symbolist and is a built-in property called his property. And all we've gotta say as if certain array has its own property and that is outside of any prototypes. Then we want to execute this code. So now we've paused this if statement. We end the block. What do we write? Well, the same thing. We want our greeting to execute that high function. And we're going to be passing in the name of the mirror. So it member list and yeah, we haven't called it. I like we did above a net old-school for-loop. Yeah, we've defined each iteration. We're going to have the name that's going to be called name. So we pass in name. Now we put our greeting and all we wanna do is console log. This greeting. And Bob's your uncle. They, we go, Welcome Tom, welcome Jerry, welcome Jon. Welcome Molly. But you can see these methods orbit cumbersome. Yahoo. You really got to think about it. You got a good amount of typing. Let me show you the for of loop, which is awesome for of loop. Okay, so let's do a for of loop. My IDE again helps me with this const iterator of object. So yeah, we've got name and I'll object is member list. And you'll see how much easier this is. This is going to loop through each name, each element of our array, of our object. All we need to do now, the trees get out greeting, which is executing the hi function. And we've already got our name. And then we can console log. Our greeting. Can you see how much easier and simpler for of loop is? Great. But I want to show you one more example now because, yeah, we've been dealing with a simple array. I want to now deal with complicated object. So let me stop this video because it's getting long. And in the next video, we're going to be dealing with the object and then we're going to iterate through debt object. See you soon.
9. Example of looping through objects: Now we're gonna go and create an object. And we're going to use those methods to convert the object into array that we saw previously. There's three different methods, and then we're going to loop through that array using the for loop. Let's see how it can be. That first step is, let's create an object. And let's just say our object is a shopping list of fruit. Let's let our fruit be an object. And I'm just going to be using the object literal syntax for the sake of simplicity. Let's say we've got 12 bananas to carrots and seven mangoes. Wii console log our fruit out. There's our object with bananas, carrots, and mangoes. How would we start iterating and looping through this data? Well, the first way is by using object dot keys. Method one. Object dot keys. Let's define our keys, LET fruit keys equal. And now we put the axes. Javascript's built in object method, object keys. And the parameter we pass into keys, the object fruit. And if we console log us out. We have literally now gonna array of our keys, manana, carrots and mangoes. And it was so easy to do and it's awesome to work with. Let's now see the second method and that is object add_values method to object dot value, late fruit values. The object. We're going to access this JavaScript built-in object and how we got values. And we pass in the fruit object once again. And if we console log this out, we get the values. Yahoo's blows my mind how simple this actually is to extract data from objects. And how you can see we've created an array in both instances, in object dot keys and object of values. We've transformed our object fruits into arrays containing the data we're interested in. But now say you wanted both the keys and the values. How would we do that? Let's weigh object dot increase comes into the picture. Let's have a look. Method3. Object interests. So now let's define fruit trees. We again have to access the JavaScript object. And how we've got increased. And we pass in the object fruit. And if we can solve this out, we get an array of arrays. Remember how I said that the dot increases almost like an array of arrays. And you can see why now, because you overall array consists of smaller arrays of key-value pairs. Okay, cool, but now how do we iterate through this fruit entries and extract both failings? Let's have a look. So if you use Object.create entries, you probably one to extract the key value pairs. And let's do a for, of loop because for off loops are awesome. And if we just did this, if we just did fruit of fruit interests, what do you think would happen? Wii console, log, fruit. Well, that's rise if you case data, it's just going to console log they array because it's going to take the first element of that overall bigger a in console log that. But what about if we want extracted? What about if we want to miss it saying, you need to buy x bananas, you need to buy two carats. How do we do that? Okay, well, what's really cool is for of loop is this fruit you can split into an array of fruit name and Froude number. I mean, you can call it whatever you want. So yeah, I've just got fruit. You know what? Let me actually make it more intuitive for you. Fruit key, set of name. Let's say that fruit key and that could be Food Valley. So you know that the ones that key in the other ones have any nets all edit is to at school it's easy. And now we should be able to console log. Let's use template literals and say you need to buy fruit. Fruit. Key. How cool is this? An aids console logs. You need about terminology, about two carats nearby, seven mangoes, they have it. So this was a really in-depth example of taking an object d structuring it out by using object keys, object values. And we even use object interests to get both the keys and values out of that object. And then once you've got an array of values, it's so easy to loop through an array. Because the for of loop, that's just very intuitive and it works amazingly well with arrays. Let's continue.
10. Shapes: We've learned about objects, we've learned about arrays. The, this lecture, it is going to be epic. But let me start off by saying that all JavaScript engines use the concepts discussed in this lecture as a way to optimize code. And as you can see from the hitting, this's shapes, but different engines call shape different things. So when you start Googling this, you may come across different terminology. Some people refer to these as hidden classes, but this is confusing because we've got JavaScript classes V8 causing maps. But this is also confusing because remember we use that map iteration. Others call them types javascript core causing structures. But spider monkey calls him shapes and just avoid confusion with other terminology after sided call them shapes as well. But anyway, I digress. We now know how objects are defined in JavaScript. We've been working with them. But in this lecture, I wanna dive deeper. I want to discuss how JavaScript engines work with objects. Looking at what we've done so far with objects, you've probably already guessed that accessing properties is by far the most common task. What do I mean when, when we have a object, let's just define a user object via the first name and last name. It's going to be very common for us to query those values. For example, user dot first name. We are asking the engine to go and fetch us the first name of this user. And because of this, it's crucial for JavaScript to make this process as quick as possible. Okay? Okay, you get it. So what is the shape? Well, let me say this. That's common to have multiple objects with the same property names or keys. For example, let's create a Dogen snake object. For example, let's say we had a dog object, hence called two keys, two names, type and age. Now we create a snake object, and it's also got type and age. It's intuitive that these two have the same shape. Those objects have the same keys. And Italy mean bow-shaped. Shapes are just objects that have the same look and feel. But let's dig deeper to understand what JavaScript does with objects. So let's create an object with properties x and y, each with a value of 1020. When we create these objects, we know that JavaScript object model is implemented. Remember we looked at the JavaScript object model and all I mean by this is that each object uses the dictionary data structure we discussed earlier. It contains the keys as strings. The keys here are x and y, and those keys point to the respective property attributes. Now, when we access the property X on that object, IE, we actually type into our code OBJ 0.8x, or in the case of our US object, we type user.name. What's going to happen. Will the JavaScript engines gonna look in the JS object for the key for that aches. And in it's going to load the corresponding property attributes. And finally, once it's done it, it's going to return the value. You see the very day in square brackets. It's gonna return net in the case of exit gonna return tin. But these property attributes. Where are they stored in memory? Let me ask you another question. Should we store these property attributes as part of their JS object? Before you answer that, let me just say what if we end up creating thousands of objects that have a similar structure, IE, that have the same shape. Out argued we really wasteful to store the full dictionary, which contains property names and associated attributes on each JS object y. Because this is going to result in a whole bunch of duplication and unnecessary memory usage. Calls. We know it wouldn't be efficient to duplicate these property attributes for every single object that has the same shape. So then what does the JavaScript engine do? Well, it stores a shape of the object and it does this separately to the actual object itself. And this shape will store all property names and attributes except for the values. Instead of storing the value property, the shape has to stall the offset value that references the chase object so that the engine knows where to find the value. And this means that every JavaScript object that has the same shape will pointing exactly this one instance does one shape instance, no duplication, and no memory leakage. And because each JavaScript object is unique, each item is going to have different values. Means that that object only has to store the unique values. Let me show you what I mean to. Let's get our object with x and y. Now, instead of that object's storing the keys, it's only going to habits values because those values are unique to it that an agonist, all the values 1020. And that object is going to be pointing to a shape. And that shape is what's gonna be storing the keys and the associated offsets. The x_max scenes. So we know when you're looking at the shape, the x points to properly attributes with an offset of Sarah. And that's why the JavaScript engine is going to know that x has a value of ten. Are you confused yet? Good. It's part of the journey to part of the journey. Perhaps this example will even be more clear once you have multiple objects. Let me show you that now we had an object OBJ, they just had x and y. Now let's create OB J1 and OB J2. So we've got two objects now, but with different values. And this is probably gonna make scenes Gina, because now we've got two objects and they boast all the unique values. But they both point to the same shape because they both have the same shape. How awesome. And you can really see now that instead of storing that information in both objects as probably attributes is only stored in one shape. Just remember, even if you're getting confused, not just remember this. No matter how many objects they are, hundreds, thousands, millions or billions. As long as they have the same shape, we only have to stall the shape and property information once. But so far we've only seen examples where we have an object and a predefined structure. We've never had to add properties to it. Which of course begs the question, what happens when we add properties to an object that has already been created? What happens to the shape? This is we transition chains and trees come into the picture. Let's create the user object. And initially illustrious sitted up, so it's empty, it's got no properties. What is its shape? Well, it's shape is also empty. So at this point in time, the user object is pointing to an in T-shape. Simple, right? But now let's add a property called name to this object with a valid John. As soon as you do this, a new shape is going to be created. The JavaScript engine now transitions to this new shape that contains the property name. The user object has a value of John as its first offset. At this point in time, it's actually the only offset. But let's keep going. Let's now add a property called age to the US object and give it a value of 38, you guessed it. Another shape is created. The JavaScript engine again transitions to this new shape that now contains both name and age. The property attributes attached to that age. It tells us that the value for age can be found at the offset one position of our user object, which makes sense. And just as a side note that if y i, the order in which properties are added to the object does impact the resulting shape. For example, we defined name and Dean age, but that's going to result in a different shade than if we had first assigned aged 38. And the name John vaccines is just going to shuffle around our shapes. In fact, another way to represent this image that you're currently looking at is the following. As you can see, we don't need to stall the full table of property attributes for each shape. Instead, if he shape only needs to know about the new property it introduces. For example, in this case, we don't have to store the information about name in the last shape because it can be found earlier in the chain. And to make us work, every shape links back to its previous shape. And this is why it's called a transition chain. It's like a chain, like one big chain with a lot of links. And all these shapes have links to each other going back. Now, in our case, what if we want to access the name property on our user object, which we know is John. When we write and user.name, the JavaScript engine is going to look up the property name by first approaching the age shape. Why? Because that's the furthest down on the chain. It's not going to find that the, so the engine's gonna keep having to walk up the transition chain until it finds the shape that introduced the name property. Makes sense. Fukuoka, now we're almost done, but I want to get a little bit more complicated. What happens if you have two objects that are first empty and then you place different properties on each of them. Will remember Holocene transition chains and transition trees. This is where the trees come into it because in this case we're going to have to branch out. Instead of having a transition chain, we can have to have a transition tree. Let me show you what I mean. Let's create a user one object. First it's NT, and then replace the property name onto it. We're going to end up with a JS object called User one that contains a single value, in this case John. And it's also going to result in harmony shapes in two shapes, S, right, the EMT shape and the shape with only a property called name. Okay, and let's create user to. User two is also going to start with an empty object, but then let's add a different property called age. What is the result of wallace? Well, we're going to have two objects, but they're going to be three. Shapes is going to be to shape chains. One related to user one and another related to user two. But let me ask you this now, does this mean is always going to be an indie shape associated with every object? No, not at all. Let me show you another example. Have a look at. Let's say we create user one, starts off as AMD and he's got a name of John. We know in this instance we're gonna have a JS object, will Valley John, that points to an empty shape that Dane transitions to a new shape with the property name of naming. We know this, but let's say we create a second user, but this time we immediately create a property called name to it. In this case, we've created an object that immediately has the name property. And this means the JavaScript engine has not had to start from an empty object and transition to a new one. It's immediately just gone to the end result. And I'm gonna make a very good point here. This is y. Object literals can be very good because this optimization and we've just seen, shortens the transition chain and makes it more efficient to construct objects from literals. Now, I want to get just a little bit more complicated. Just bear with me. Hold on tight, don't stop. Now, you're almost done. Answers, very reasonable information, very interesting. Let's create a user object with three properties now, name, age and bold, luscious eighties, ball them up. As we learned before, this creates an object with how many shapes? With four shapes in memory. That's right. And now to access the property name on that object, the JavaScript engine needs to follow the linked list. It's going to have to start with the shape at the very bottom. And then it's going to have to work its way up to the shape that introduced name, which is where the top. And as I'm sure you've already guessed, this is going to be if we do this more often, especially when the objects have a lot of properties. So to speed up searching for properties that JavaScript engine, Ed's a shape table data structure. And the shape table is a dictionary mapping property keys to the respective shapes that introduced the given property. Here is the shape table and what it looks like. In effect, that's another kind of dictionary that shortens this whole process. For example, you can see on the screen at the shake table, will tell the JavaScript engine way to find these property values in which shape to find these property values. So in research for the name, it's still starts in the shape, in the later shape. But at later Shape Points to shake table. And they, the JavaScript engine knows to look in which shaped find that name property. It's making saints router. Cannot believe it or you serious. Now we've got another shape table. Thought the whole reason for shapes was devoid or dictionary lookup. Now we've got another one. Allele aren't ghettos. Camps gonna give up. No, don't give up and know the answer. And the reason is that the shape table and nice shapes are a means to an end and that is to enable inline caches. Inline caches or the true secret behind JavaScript's runtime environment makes jaws ripped so fast. And I don't wanna go into too much detail inline caches because that's a whole topic in and of itself. But I hope I've given you enough flavor and enough knowledge so you can dig deeper into this topic that interests you. But we're not quite done with this Legion because a, I want to show you what a shake table looks like. In B. I just want to introduce but more to the concept of an inline cache and what it actually means that it very, very highly, sir, just yellow coffee. We've only got one minute left or two minutes left. Mex of this lecture. It's hanging. Let's get back into it. And I don't wanna get into inland caches. We know that it's another whole topic in and of itself that is at a very high level, this is how I like to think of it. Say we create a function called taste that takes in a user object and we just console logging the user's name out. When you execute the function for the first time, the inline cache would look up the property name and find that value is stored at offset 0. Because we know the user one object has the name John, in this case at offset 0. When you execute that function, it's going to find that offset. And the inline cache will memorize the shape and the offset at which their property was bombed. So when you look at the j is function taste, it's gonna stall that offset Zara in that function call. And what this means is that if the JavaScript engine sees objects with the shape that the inline cache recorded before, it no longer needs to reach out to the property information at all. Instead, the expensive property information lookup can be skipped entirely. And this is significantly faster than looking up the property each time. Let me show you what I mean. So shall we set up the test function with Calderon user one and the inline caches toward the offset 0 in the function itself. Now, when we call it on user two, what do you think's going to happen? Well, in this case, the inline caches gonna recognize it. It's got the same shape. And instead of having to look up the property attributes and go to the shape tables, et cetera, et cetera. But knows the devil said 0. So all it does is it takes it inline cache of Zara and it returns a value Ali, from that object. Cool, right? Anyway, there's very high level of inline caches. You don't have to really understand it too much in depth now, but if you do want to dig deeper, Herbert, given you enough of a flavor. Well, this has been a long lecture, so thanks for bearing with me. Well Dan, if you've got this far, just want to recap quickly. We've learned how JavaScript engines store objects and arrays, and how shapes and inland caches helped to optimize operations on these objects. And based on this knowledge, what can we take away from it? Well, if there's one thing we can take away from this practical, we miss just initialize our objects in the same way. So they don't end up having different shapes. For example, if you want to create a user objects, don't create one with a property of name, another one with a fname, Another one of first name. And other ones are first and then a capital N for name there. So we're going to have different shapes and it's gonna make things more complicated. And so the background rather be consistent in how you initialize your objects goal. I hope this has been very informative. T, i? A lot of fun putting it together because quite a complicated topic and not many people know about it, so yeah, enjoy it. And let's move on. Let's get into some more JavaScript to see you soon.