Creating and initializing Arrays

Arrays are a collection of elements of the same type. You can create an array by using square brackets [ ], and separate the values with commas.

Loading Code . . .

You can also create an array with other arrays inside of it.

Loading Code . . .

Why use Arrays?

Arrays are useful when you want to store a list of values. For example, imagine you want to create a shopping list. Without an array, you would have to create a variable for each item.

Loading Code . . .

In the code above, we have created three variables to store the items in our shopping list. If we want to add more items to our list, we would have to create more variables. This is not very efficient, and limits the number of items we can store in our list.

And this limitation would be a problem for a lot of applications. For example:

  • A list of contacts in a phone book
  • A game that has a list of items that the player can collect
  • A list of videos that a user can watch in a video streaming service
  • A list of addresses that a user can select from to send a package
  • A list of credit card numbers that a user can select from to make a payment
  • A list of friends in a social network

Let's see how we can use an array to store our shopping list.

Loading Code . . .

In the code above, we have created an array called items and stored our shopping list in it. We can do a lot of awesome things with arrays, like:

  • Add items to any position in the array
  • Remove items from any position in the array
  • Update items in the array
  • Use loops to iterate through the array and do something with each item

So, everytime you want to store a list of values, or think you might need a lot of variables with the same type (like item1, item2, item3, etc.), you should consider using an array.


Code Time!

Now, create an array called myArray and store the following values in it:

  • "Hello"
  • 25
  • true
Loading...

© 2024 - ®Mewters