Course Content
Introduction to JavaScript
Introduction to JavaScript
Array
The array is the most useful data structure.
Note
A data structure is a specialized format for organizing and working with data collection. An array is a collection of items where each item is a value.
Creating an Array
To create an array, use square brackets []
:
This creates an empty array with no elements. To create an array with elements, place the elements inside []
and separate them with commas (,
):
Note
The last element in the array should not have a comma after it.
To print an array, simply use console.log()
:
const arr = [1, 2, 3, 4, 5]; console.log(arr);
Indexes
Each element in an array has a unique index.
Note
Indexes start from 0. The first element has an index of 0, the second element has an index of 1, and so on.
Accessing array data is done by specifying the index in square brackets ([index]
) after the array name:
const arr = [1, 2, 3, 4, 5]; const thirdElement = arr[2]; // retrieving the 3rd element console.log(thirdElement);
Arrays can hold different data types, including number, string, boolean, and more.
const arr = [2441.23, "Hello!", false]; console.log(arr[0]); console.log(arr[1]); console.log(arr[2]);
Length Property
The length
property is a built-in property of arrays that represents the number of elements in that array. To use this property, use the following syntax:
const arr1 = [10, 20, 30]; const arr2 = [15, 25, 35, 45, 55]; const x = arr1.length; // `x` variable represents the `arr1` length const y = arr2.length; // `y` variable represents the `arr2` length console.log(x); console.log(y);
Thanks for your feedback!