Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

5 Arrays

1 Arrays

A variable can hold a single value, however, if we are required to store marks of 100 students, we will have to create 100 separate variables to store marks. For example:

var student1_marks = 100;
var student2_marks = 90;
var student3_marks = 80;
var student4_marks = 90;
//..... Continue

Creating separate variables means creating 100 memory blocks in the computer memory and accessing them separately.

Using an array allows us to store all the marks in a single variable. Each mark is stored as an element of the array, making it easier to manage and access the data. This approach is more efficient in terms of memory usage and allows for easier manipulation of the data, such as sorting or iterating over the marks of all students.

Arrays are essential data structures in programming, designed to store collections of elements, typically of the same type. They offer a convenient way to manage and manipulate groups of data efficiently.

In an array, elements are organized in a linear sequence and accessed using an index. Each element occupies a unique position within the array, with indexing starting from zero for the first element.

// Example: Declaring an array named 'numbers' to store integers
let numbers = [10, 20, 30, 40, 50];

To retrieve a specific element from an array, you can access it using its index. For instance:

let numbers = [10, 20, 30, 40, 50];
console.log(numbers[2]); // Output: 30

This code snippet retrieves and prints the value at index 2, which is 30.

An array has built-in methods called push() and pop() that allow you to add and remove elements from the end of an array, respectively.

push():

The push() method adds an element to the end of the array.

Here's an example of how to use the push() method:

// Using push() to add an element to the end of the array
let numbers = [10, 20, 30, 40, 50];
numbers.push(90); // Adds the element 90 to the end of the array

console.log(numbers); // Output: [10, 20, 30, 40, 50, 90];

pop():

The pop() method removes an element from the end of the array.

Here's an example of how to use the pop() method:

// Using pop() to remove the last element from the array
let numbers = [10, 20, 30, 40, 50];
numbers.pop(); // Removes the last element from the array

console.log(numbers); // Output: [10, 20, 30, 40];

Arrays provide a versatile way to manage collections of data, facilitating operations such as iteration, searching, sorting, and more.