Skip to content

Latest commit

 

History

History
86 lines (56 loc) · 2.5 KB

array.md

File metadata and controls

86 lines (56 loc) · 2.5 KB

🔓 Array

We use array to store list of items.

Let's try making a list of colour using array.

✔️ First of all we need to declare a variable name colours and assign it with a square bracket [ ].

let colours = [];

So the square brackets [ ] are called the array literals and they indicate an empty array.


✔️ Now, let's fill in the arrays with some colours and use console.log() to show your colours in the console.

let colours = ["red", "orange", "yellow", "green", "violet"];
console.log(colours);

This is the output in the console



You will see this by expanding the array



You will see an array of the 5 elements and each have them have an index number that determines the position of each colour in the array.


✔️ If i were to display the last element in the array, i use the index number to call them. This is how:

console.log(colours[4]);

and I will see violet in the console.


✔️ Let's try adding colour 'blue' into the array.

ℹ️ Since the index number for the last item is 4, adding a new colour into the list will take up index 5. Therefore, we assign index number 5 with 'blue'.


Copy the code below and check if you get the same output as shown in the console tab.

Adding and element

colours[5] = "blue";

And you should see this in your console.




✔️ In JavaScript we can store different types of data in an array. You can try adding a number at the end of the list. This is how you can do it, and the output is shown in the console tab.

try this line of code:

colours[6] = 123;
console.log(colours);

Result in console







◀️ Previous Page : Basics of JavaScript : Arithmetic Operators 🔓             🏡            ▶️ Next Page : Control Flow : Conditional Statements 🚩 🔓