Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Array | Variables and Data Types
Introduction to JavaScript
course content

Course Content

Introduction to JavaScript

Introduction to JavaScript

1. Basic Concepts
2. Variables and Data Types
3. Basic Operations
4. Conditional Statements
5. Loops
6. Functions

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

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

12345
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.

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

123456789
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);
1. Which brackets are used to create an array?
2. Retrieve the second element from the array:
3. How do you get the length of the array?

Which brackets are used to create an array?

Select the correct answer

Retrieve the second element from the array:

Select the correct answer

How do you get the length of the array?

Select the correct answer

Everything was clear?

Section 2. Chapter 6
We're sorry to hear that something went wrong. What happened?
some-alt