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:
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.
1const firstElement = array[0];
2console.log(firstElement); // Output: 1Arrays also support updating elements. You can assign a new value to an element by using its index.
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.
1const length = array.length;
2console.log(length); // Output: 5To 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].
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.
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.
1const lastElement = array.pop();
2console.log(lastElement); // Output: 6
3console.log(array); // Output: [1, 2, 10, 4, 5]xxxxxxxxxxconst array = [1, 2, 3, 4, 5];// accessing an array elementconst firstElement = array[0];console.log(firstElement); // Output: 1// updating an array elementarray[2] = 10;console.log(array); // Output: [1, 2, 10, 4, 5]// finding the length of an arrayconst length = array.length;console.log(length); // Output: 5// iterating over an arrayfor (let i = 0; i < array.length; i++) { console.log(array[i]);}// adding an element at the end of an arrayarray.push(6);console.log(array); // Output: [1, 2, 10, 4, 5, 6]// removing the last element of an arrayconst lastElement = array.pop();console.log(lastElement); // Output: 6console.log(array); // Output: [1, 2, 10, 4, 5]


