Loading
Lesson 21
Courses / JavaScript for Complete Beginners
Accessing JavaScript Array Elements

Video Transcript

So, this position number here for each item in this list is called the array index. So, at index sub zero we have the item John, index sub one, we have the item Anna, index sub two, have the item Andrew. Notice we always count starting from zero, okay? And this always follows the order in which the array is defined. So, it's an order list, okay? Keep that in mind. There's a specific order, a specific sequence. So, also, just so you know, we are only using strings here as each element of the array, but that's not necessarily the case for every single array that you define. You can define an array of any kind of type, okay? Could be a number, could be an object, or even an array of arrays. So, it just so happens that our example here uses strings, okay? Now that we know how to define an array, we have to learn how to access each of these specific elements in the array individually. So, the way to do that is using two brackets after the name of the variable that holds the array. In this case, we are holding this array in a variable called names. So, if you want to access, for example, Anna inside this array, you have to add square brackets here, then inside you have to tell it the position index. So remember, we look before, y'all's count started from zero. So, if you want Anna, you have to start here at the beginning of the array. So, the first element is John. The index is zero. So, if you go to Anna, now the index is one. You increment, right? So, to get Anna, I will have to tell it to go to index one. At index one, we're going to get whatever is there in this slot. In this case, it's the string Anna. Okay? In a similar fashion, you can get the first element and then the last element. I'll leave it to you as an exercise. So, pause the video and try to get first John and then try to get only Andrew. So, how did it go? So to get John, simply reference the name of variable, square brackets, then the index. This case is going to be zero. To get Andrew, that's the last item. In this list, it's going to be sub what? You count from the first zero is John, one is Anna, and two is Andrew. So it has to be two. Okay? So, that's how we access individual elements of an array. And, if you remember type of operator we used before, you can try to tell, okay, what's the type of names and it will tell you it's an object. And this is because the array is actually a special type of object in JavaScript. So keep that in mind, all right? So an array is just a special kind of object in JavaScript. We haven't really talked much about object, but just keep that the back of your head.
No comments yet (loading...)
No comments yet (loading...)
Did you like the lesson? 😆👍
Consider a donation to support our work: