JavaScript - 7
JavaScript - 7: Arrays
An array lets you store several values together inside one variable.
Instead of creating a separate variable for every item, you can place related values inside square brackets and access them by position.
Your challenge: Create an array called fruits with at least four fruit names, then print the whole array, the first fruit, and the total number of items.
What is an array?
An array is a single value that can contain several other values.
For example: let fruits = ["Apple", "Banana", "Mango", "Orange"];
The square brackets [ ] mark the beginning and end of the array, and commas separate the items.
Arrays have positions called indexes
Every item in an array has a numbered position called an index.
JavaScript starts counting array indexes at 0, not 1.
So in: ["Apple", "Banana", "Mango"]
Apple is at index 0,Banana is at index 1,
and Mango is at index 2.
Access the first item:
To get the first fruit, use: fruits[0]
The square brackets after the array name tell JavaScript which position you want.
Try: console.log("First fruit:", fruits[0]);
Try another index:
If your array contains at least four items, try: fruits[2] or fruits[3].
Notice that index 2 gives you the third item because counting started at zero.
Count the items with .length
Arrays have a useful property called length.
For example: fruits.length returns the number of items inside the array.
Unlike indexes, length gives the normal item count. If the array contains five fruits, its length is 5.
Print the whole array:
You can pass the entire array to console.log(): console.log("All fruits:", fruits);
This is useful when you want to inspect everything stored inside an array.
Change an item:
You can replace an existing value by assigning a new one to its index.
For example: fruits[0] = "Peach";
Now the first item is "Peach" instead of its previous value.
Add an item with push():
Arrays can also grow.
Try: fruits.push("Pear");
This adds "Pear" to the end of the array.
Then print: fruits.length again and notice that the total has increased.
Experiment: Create another array called colors with three color names.
Print the second color using index 1, then print the total number of colors.
Good JavaScript habit: Use arrays when several values belong to the same group. A variable called fruits containing several fruit names is usually easier to manage than separate variables such as fruit1, fruit2, and fruit3.
👀 Show Solution
let fruits = ["Apple", "Banana", "Mango", "Orange", "Pineapple"];
console.log("All fruits:", fruits);
console.log("First fruit:", fruits[0]);
console.log("Total fruits:", fruits.length);The array stores five fruit names in one variable. fruits[0] accesses the first item, while fruits.length returns the total number of items.
Remember that array indexes begin at 0, even though length counts the actual number of items.
