Mark As Completed Discussion

Arrays: Introduction and Basic Operations

In the world of programming, arrays are one of the most commonly used data structures. They provide a way to store multiple values of the same type in a single variable.

Arrays are like a collection of boxes, each containing a value. You can think of a box in the array as an element. The elements in an array are indexed starting from 0, which means the first element is at index 0, the second element at index 1, and so on.

For example, consider the following array:

PYTHON
1const array = [1, 2, 3, 4, 5];

To access the first element of the array, you can use array[0]. In this case, it will return the value 1. Similarly, you can access other elements by specifying their index.

PYTHON
1const firstElement = array[0];
2console.log(firstElement); // Output: 1

Arrays also support updating elements. You can assign a new value to an element by using its index.

PYTHON
1array[2] = 10;
2console.log(array); // Output: [1, 2, 10, 4, 5]

The length property of an array gives you the number of elements it contains. You can access it using the length property.

PYTHON
1const length = array.length;
2console.log(length); // Output: 5

To iterate over an array, you can use a for loop. The loop condition should be i < array.length, and you can access the elements using array[i].

PYTHON
1for (let i = 0; i < array.length; i++) {
2  console.log(array[i]);
3}

You can add elements to the end of an array using the push method.

PYTHON
1array.push(6);
2console.log(array); // Output: [1, 2, 10, 4, 5, 6]

To remove the last element of an array, you can use the pop method. It removes the last element and returns it.

PYTHON
1const lastElement = array.pop();
2console.log(lastElement); // Output: 6
3console.log(array); // Output: [1, 2, 10, 4, 5]
PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment