Arrays Vs Objects in Javascript Part-1.
If you are a beginner and confused between Arrays And Objects in JS, here I'm to make it simple for you.
Hello everyone, hope you all doing fine. I'm writing my first blog and if you find something wrong in my blog, please forgive me for that and point out my mistake in the comment section.
This topic is long so I have separated my blog into two parts. This is a Part-1 from point-1 to point-5 and for Part-2 π Click Here!
When I'm a beginner then I keep getting mixed up with Arrays
and Object
in JS. And if you are also on the same path, then here I break down the whole topic into smaller subtopics, so that next time you don't get confused.
We will therefore discuss the following topics below: -
- Intro to Arrays in JS
- Creating a Arrays
- Array Random Access
- Array Methods
- Nested Array
- Intro to Objects
- Creating Object Literals
- Accessing Data Out of Objects
- Modifying Objects
- Nesting of Arrays and Objects
Note: This blog is going to be long so sit back and relax, and enjoy the entire blog with popcorn π. And I assume that you know some basic programming in any language, but still, it will be easy to understand if you do not know much about it.
1. Intro to Arrays in JS
So Arrays allow us to group data to store one or more of the same type or mix types, both together at a time. Examples of an ordered collection of values:
- Songs in a playlist.
- List of comments on Instagram Post.
- Collection of levels in a game.
Arrays are kind of like these, which means it's just a bunch of slots we can put things into, but there's an order. Those are the two key concepts of an array:
- Collection of values.
- It is an ordered collection of values.
2. Creating a Arrays
To make an empty array
let students = [];
An array of strings
let colors = ['red', 'orange', 'yellow'];
An array of numbers
let students = [55, 18, 259, 8, 0];
A mixed array
let anyStuff = [true, 69, 'cat', null];
So in the
anyStuff
array following values are:boolean, number, string, null
Note: Please don't confuse if you haven't read about the
let
keyword, we can also usevar
orconst
. Please watch this π Click Hereπ to know more about these keywords in JS.
As we find the length of a string, We can also find Arrays length
When the array has some data
But what happen when there is no data
So in an empty array javascript will not give any error, it simply gives arrays length equal to 0
.
Note: In an array, we can even put other arrays inside the array in Javascript. Which we'll talk about later.
3. Array Random Access
So now we talk about, how we access our data in arrays. Sometimes we put our data in order or sometimes we don't care about order.When we put our data inside an array then each element is assigned with an
index
just like strings.
Basically in a string, each character
is assigned an index
and in an array, each individual element has its own index
.
let anyStuff = [true, 68, "dog", null];
Below is the index
number for each element in an array above:
index(0)
- trueindex(1)
- 68index(2)
- "dog"index(3)
- null
Note: So just like a string, our count for
index
starts from zero, and it's the same here.
Therefore, theseindices
are important because we use them to refer to a specific element in an array.
a). Let see how we access data from an array:
- As we know, our array size is
four
. Ourindexes
will therefore be zero to three only and we can access the data in any order ofindexes
.
b). What happens, when we access that index
which is not present in the array:
- Remember that Index 7 is not here and will just return
undefined
. That means we have nothing to see here.
c). What will happen if we want to have access to an index of index data:
d). Until now we have seen how to access data. But what, if we want to update data in an existing array:
e). We can update all the new data in a new index
, which is not included in this array:
"empty Γ 4"
means: 4 empty slot and then our data "Thursdays" in index 9. And if you want to access, any of them days[5]/days[6]/days[7]/days[8] than it will give you undefined, because in these indices there is no current data available in our array.
4. Array Methods
Now we see some built-in array methods. Our browser provides a pre-defined set of methods for us to easily access. You may refer to all array methods here π Click HereNow we see a couple of main methods here:
Push
- add to the endPop
- remove from the endShift
- remove from the startUnshift
- add to startPush:
Push
allows us to add from the end of an array. At the very end, not at the start likeStack
(like in DSA).- As mentioned above, a method for adding a new element in the array is:
let fruits = ["π", "π₯"]; fruits[2] = "π"; console.log(fruits); // 'π', 'π₯', 'π'
- Now we can also add a new item as follows, no need to know the index number in this method.
let fruits = ["π", "π₯"]; fruits.push("π"); console.log(fruits); // 'π', 'π₯', 'π'
- Using this method, we can add more than one data at the same time into the same array.
let fruits = ["π", "π₯"]; fruits.push("π", "π"); console.log(fruits); // 'π', 'π₯', 'π', 'π'
Note: All these data, in the
Push
method, are added on the back of our array.
Pop:
Like
Push
,Pop
also allows us to remove data at the end of an array.
AndPop
requires no argument likePush
because it knows that we have to delete data at the very end of an array.let sports = ["π", "β½", "π₯"]; sports.pop(); console.log(sports); // 'π', 'β½'
Note:
- So think of these methods(
Push
&Pop
) asStack
. Last In First Out. - You can create an array with those methods. Simply declare an empty array and then
push
to add element &pop
for removing element.
- So think of these methods(
Shift:
Shift
andUnshift
are also pairs that operate at the start of an array.
Therefore, essentially,shift
removes the element at the beginning of an array. This is likepop
or deletes from the start of an array.let sports = ["π", "β½", "π₯"]; sports.shift(); console.log(sports); // 'β½', 'π₯'
Unshift:
Add a new element at the start of an array.
let sports = ["π", "β½", "π₯"]; sports.unshift("πΎ"); console.log(sports); // 'πΎ', 'π', 'β½', 'π₯'
Note: Consider these methods (
Shift
&Unshift
) asQueue
. First In First Out.A few more methods that are commonly used:
concat
- add two arrays together click to know moreincludes
- this is a boolean method, check whether the item is present in the array or not click to know moreindexof
- it gives the index of the element of an array click to know morereverse
- it reverses an all element of an array click to know moreslice
- it's a way to get a copy of part of an array click to know moresplice
- it does a little bit more. It modifies the contents of a table by deleting or substituting existing elements click to know moresort
- as the word suggests it sorts the elements of a set array and returns the sorted array click to know moreA few more methods that are commonly asked in the JS interview:
map
- without changing the original array it returns a new array by calling a function for each element in an array click to know morefilter
- create a new array with all elements that pass a test provided by a function click to know morereduce
- it is a method that accepts 2 arguments first is thecallback
function and the other optional argument is known as the initial value click to know morefind
- it returns the value of the first element in the array that satisfies the provided function click to know moreforEach
- execute provided function for every element of provided array click to know moreStill confuse among
map
,filter
&reduce
then watch this video π Click Here
Note: Must read about double equal operator
(==)
and triple equal operator(===)
and there use case in the array. Click Here To Know More
5. Nested Array
As I mentioned earlier that arrays can store any type of data, they can storeprimitive
like strings
, numbers
, boolean
, null
, and undefined
, but they can also store more data structures like arrays
.
They can also store the
object
, as we shall see later.
Let's look at some nested arrays. Two levels of arrays. Arrays with a bunch of arrays.
let colors = [ ['Red', 'Black'], ['Blue', 'Green'], ['Gold', 'Gray'], ['Orange', 'Yellow'], ['Purple', 'Salmon'] ];
Now the question is how we access data from
Nested Array
?- In order to access data, we need to go through two levels of an array.
colors[2]; // so this return 3rd array list from colors array // ['Gold', 'Gray'] // now I want to access 'Gray' from this list. Let's see how we do that colors[2][1]; // 'Gray'
- If we have a 3D array, then we can fetch the access of the center item from a 3D array. And so forth for greater dimensions.
colors[1][1][1];
Till here we have learned about Arrays in JS
which is Part-1 of this topic. Now, take a five-minute break and give the brain a little rest and come back again, and then we'll figure out Object in JS
in Part-2.
Thank you, guys! that's it in part-1 and I hope this blog helped you to clear all your confusion regarding Arrays
in JS and if it was helpful, please provide Like, Share, And Comment, to promote this article to more people.
Follow me on Twitter for interesting threadsπ₯
For Part-2 Of This Topic π Click Here!
To Read More Topics In JS Article Series π Click Here!
I attach some references below if you want to deep dive into: