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:
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:
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:
You can also modify individual elements in an array by assigning a new value to their index, like this:
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:
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:
Hint: You can use a for
loop to iterate through the array and add up the numbers.
Last updated