Array

In JavaScript, an array is a special data type that is used to store a collection of elements, such as numbers, strings, or even other arrays. Each element in the array is assigned an index, which starts at 0 for the first element and increments by 1 for each subsequent element.

To create an array in JavaScript, you can use the square bracket notation like this:

let myArray = [1, 2, 3, 4, 5];

This creates an array with 5 elements, each containing a number from 1 to 5. You can also create an empty array and add elements to it later like this:

let myEmptyArray = [];
myEmptyArray.push(1);
myEmptyArray.push(2);
myEmptyArray.push(3);

This creates an empty array and then adds the numbers 1, 2, and 3 to it using the .push() method.

You can access individual elements in an array using their index, like this:

let myArray = [1, 2, 3, 4, 5];
console.log(myArray[0]); // outputs 1
console.log(myArray[3]); // outputs 4

You can also modify individual elements in an array by assigning a new value to their index, like this:

let myArray = [1, 2, 3, 4, 5];
myArray[2] = 10;
console.log(myArray); // outputs [1, 2, 10, 4, 5]

You can also use various built-in methods to manipulate arrays, such as .push() to add an element to the end of the array, .pop() to remove the last element from the array, .shift() to remove the first element from the array, and .unshift() to add an element to the beginning of the array.

Here are some examples of using these methods:

let myArray = [1, 2, 3, 4, 5];
myArray.push(6); // adds 6 to the end of the array
myArray.pop(); // removes 6 from the end of the array
myArray.shift(); // removes 1 from the beginning of the array
myArray.unshift(0); // adds 0 to the beginning of the array
console.log(myArray); // outputs [0, 2, 3, 4, 5]

A basic array problem for you to practice

Write a function called sumArray that takes an array of numbers as an argument and returns the sum of all the numbers in the array.

Example usage:

sumArray([1, 2, 3, 4, 5]); // returns 15
sumArray([10, -5, 7, 9]); // returns 21
sumArray([]); // returns 0

Hint: You can use a for loop to iterate through the array and add up the numbers.

Last updated