Arrays Vs Objects in Javascript Part-1.

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.

Β·

9 min read

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: -

  1. Intro to Arrays in JS
  2. Creating a Arrays
  3. Array Random Access
  4. Array Methods
  5. Nested Array
  6. Intro to Objects
  7. Creating Object Literals
  8. Accessing Data Out of Objects
  9. Modifying Objects
  10. 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:

  1. Collection of values.
  2. 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 use var or const. 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
    Arrays-JS1.jpg


  • But what happen when there is no data
    Arrays-JS2.jpg

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) - true
  • index(1) - 68
  • index(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, these indices 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:

Accessing Data.jpg

  • As we know, our array size is four. Our indexes will therefore be zero to three only and we can access the data in any order of indexes.

b). What happens, when we access that index which is not present in the array:

index fail to access.jpg

  • 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:

accessing index of index.jpg

d). Until now we have seen how to access data. But what, if we want to update data in an existing array:

update data.jpg

e). We can update all the new data in a new index, which is not included in this array:

update data new index.jpg

  • "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 Here

Now we see a couple of main methods here:

  • Push - add to the end
  • Pop - remove from the end
  • Shift - remove from the start
  • Unshift - add to start
  • Push:

    Push allows us to add from the end of an array. At the very end, not at the start like Stack(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.
    And Pop requires no argument like Push because it knows that we have to delete data at the very end of an array.

    let sports = ["🏏", "⚽", "πŸ₯Š"];
    sports.pop();
    console.log(sports);
    // '🏏', '⚽'
    

    Note:

    1. So think of these methods(Push & Pop) as Stack. Last In First Out.
    2. You can create an array with those methods. Simply declare an empty array and then push to add element & pop for removing element.
  • Shift:

    Shift and Unshift 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 like pop 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) as Queue. First In First Out.

  • A few more methods that are commonly used:

  • concat - add two arrays together click to know more
  • includes - this is a boolean method, check whether the item is present in the array or not click to know more
  • indexof - it gives the index of the element of an array click to know more
  • reverse - it reverses an all element of an array click to know more
  • slice - it's a way to get a copy of part of an array click to know more
  • splice - it does a little bit more. It modifies the contents of a table by deleting or substituting existing elements click to know more
  • sort - as the word suggests it sorts the elements of a set array and returns the sorted array click to know more

  • A 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 more
  • filter - create a new array with all elements that pass a test provided by a function click to know more
  • reduce - it is a method that accepts 2 arguments first is the callback function and the other optional argument is known as the initial value click to know more
  • find - it returns the value of the first element in the array that satisfies the provided function click to know more
  • forEach - execute provided function for every element of provided array click to know more

    Still 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 store primitive 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:

MDN Docs for Arrays

If you found my article helpful, than πŸ‘‡

Buy Me A Coffee

Β