Arrays in javascript & its methods

Arrays in javascript & its methods

Arrays in Computer Science

Definition: Arrays are blocks of contiguous space in memory. which stores variables of the same data type

This definition appears to be quite technical at first, but consider it as an overall problem. In general, splitting a problem into smaller pieces and then attempting to solve it is a wiser way to approach problem solving.

Let's start with "Arrays are blocks of contiguous memory space." To comprehend this line, first study how the computer's memory system works.

Memory

Inside our computers, we have chips called RAM (random-access memory) that store zeroes and ones. And there are a series of ones and zeros in which the computer stores any kind of data. The sequence of eight zeros and ones is called a byte. We can think of bytes stored in RAM as though they were in a grid, one after the other, as shown in the example.

ram.png

Let's write a small program and then have a look at how the computer stores this in memory.

let number1 = 20;
let number2 = 25;
let number3 = 50;
let average = (number1 + number2 + number3) / 3;
console.log(average);

Now, when we assign a value to a variable, we are telling our computer to store that number in its memory. Now in this case, we are telling our computer to store numbers 20, 25, and 50 in memory. For simplicity, I have taken only a number, which takes a byte of memory.

ram.jpg

Here, when the computer stores this variable, it can store it anywhere in the memory. This value is linked with their variable name. To store three values, we are taking memory for variables and the corresponding value of each variable. Storing data in this form won't cause any problems for smaller amounts of data. Now imagine how many variables we're going to need to store a large amount of data. Consider making a phone book: It will be more challenging to assign those values to variables because there will be millions of records in one place. The solution to this problem came in the form of arrays.

Array

Let's write the exact same code we did before, but this time, let's write it as an array.

let numbers = [ 20, 25, 50 ];
let average = (numbers[0] + numbers[1] + numbers[2]) / 3 ;
console.log(average);

As we can see this time, we stored our data in one variable, which is numbers. and put all of our values inside [ ] brackets. This program is looking more clean, isn't it ? Now let's see how arrays are stored in memory.

ram (1).jpg

This time our values will be stored in order, one after another. Our values are going to be stored continuously in memory. means the computer doesn't have to worry about linking all values in different variables; it is going to store them in just one variable. And to access them, we're going to use what we call indexing.

indexing

index is nothing but at what location our data is stores in an array. This location is represented in the form of numbers, which start from 0 and go up to 1, 2, 3,... one number less than the length of the array. Now in our second program, the index for 20 is 0, for 25 is 1, and for 50 is 2. Many of you must be wondering why the index starts with zero and not one. In the past, people who made programming languages thought of it as its going to start from zero index, there reasoning were how much far the number is from first element. The number 50 in our array is 2 units away from our first element, which is 20.

template (1).jpg

Now we have the knowledge to understand the first line of definition. "Arrays are blocks of contiguous space in memory." Blocks are memory allocated to a variable. In our example, if numbers 20, 25, or 50 needed a byte of memory, it could be different for different data types. The word "contiguous space" means the memory that's going to be taken is going to be one after the other.

Now talking about the other half of the definition, "which stores variables of the same data type," in our example we have taken numbers as our example. They are all numbers of the same type. But in modern programming languages like JavaScript, we can store variables of any data type in an array like strings, Boolean, numbers, etc.

So we can say that an array in JavaScript is an object that can store multiple values at once. For example, const words = ["hello," "world," "welcome"];

Creating a variable

array can be created by two methods in JavaScript.

  1. Using an array literal
  2. Using the new keyword

1. Using an array literal

The easiest way to create an array is by using an array literal

const array = ["hello", "LCO"];

2. Using the new keyword

You can also create an array using JavaScript's new keyword.

const array = new Array("hello", "LCO");

Access Elements of an Array

You can access elements of an array using indices (0, 1, 2 …).

const Array = ['h', 'e', 'l', 'l', 'o'];

// first element
console.log(Array[0]);      // "h"

// second element
console.log(Array[1]);      // "e"

// third element 
console.log(Array[2]);      // "l"

// third element 
console.log(Array[3]);       // "l"

// third element 
console.log(Array[4]);       // "o"

Methods for array in JavaScript

Method is a property of an object that contains a function definition. means there are certain functions made by coders of JavaScript. which we can access for doing certain tasks

Add an element to an array.

You can use the built-in methods push() and unshift() to add elements to an array. The push() method adds an element at the end of the array.

let todo = [  'eat', 'code', 'sleep' ];

// add an element at the end
todo.push('exercise');

console.log(todo);      //  [ 'eat', 'code', 'sleep', 'exercise']

The unshift() method adds an element at the beginning of the array.

let todo = [  'eat', 'code', 'sleep' ];

// add an element at the end
todo.unshift('exercise');

console.log(todo);      //  [ 'exercise', 'eat', 'code', 'sleep' ]

Change the Elements of an Array

You can also add elements or change the elements by accessing the index value.

let todo = [ 'eat', 'sleep'];
// this will add the new element 'exercise' at the 1 index
todo[1] = 'exercise';
console.log(todo); // ['eat',  'exercise' ]

Remove an element from an array

You can use the pop() method to remove the last element from an array. The pop() method also returns the returned value.

let todo = ['work', 'eat', 'sleep', 'exercise'];

// remove the last element
todo.pop();
console.log(todo);   // ['work', 'eat', 'sleep']

// remove the last element from ['work', 'eat', 'sleep']
const removedElement = todo.pop();

//get removed element
console.log(removedElement);  // 'sleep'
console.log(todo);  // ['work', 'eat']

If you need to remove the first element, you can use the shift() method. The shift() method removes the first element and also returns the removed element.

Array length

You can find the length of an element (the number of elements in an array) using the length property.

const todo = [ 'sleep', 'sleep again'];

// this gives the total number of elements in an array
console.log(todo.length); // 2

Some important methods for arrays

  • indexOf() - searches an element of an array and returns its position

  • concat() - joins two or more arrays and returns a result

  • find() - eturns the first value of an array element that passes a test

  • findIndex()-returns the first index of an array element that passes a test

  • forEach() -calls a function for each element

  • includes() checks if an array contains a specified element

  • push() aads a new element to the end of an array and returns the new length of an array

  • unshift() adds a new element to the beginning of an array and returns the new length of an array

  • pop() removes the last element of an array and returns the removed element

  • shift() removes the first element of an array and returns the removed element

  • sort() sorts the elements alphabetically in strings and in ascending order

  • slice() selects the part of an array and returns the new array

  • splice() removes or replaces existing elements and/or adds new elements