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:
letmyArray= [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:
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.
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]