Arrays in JavaScript

Arrays in JavaScript

Introduction:-

Arrays in JavaScript are versatile data structures that allow you to store and manipulate collections of items. Let's explore the fundamentals of arrays and some essential methods for working with them.

Declaring Arrays:-

  • You can declare an array using square brackets or the Array constructor:
const myArr = [1, 2, 3, "pashuapti", true];
const myNew = new Array(1, 2, true, "hello");

Accessing Array Elements:-

  • Arrays in JavaScript use zero-based indexing. You can access elements by their index
console.log(myArr[2]); // Output: 3

Array Manipulation:-

  • JavaScript provides various methods for manipulating arrays:

Adding Elements:

myArr.push(4); // Add 4 at the end
  • The push method adds an element to the end of the array.

Removing Elements:

myArr.pop(); // Removes the last element
  • The pop method removes the last element from the array.

Adding Elements at the Beginning:

myArr.unshift(8); // Add 8 at the start
  • The unshift method adds an element to the beginning of the array.

Removing Elements from the Beginning:

myArr.shift(); // Remove the first element
  • The shift method removes the first element from the array.

Slice and Splice:

1) slice(start, end):-

const mySlice = myArr.slice(1, 3); // Returns elements from index 1 to 2
  • The slice method returns a shallow copy of a portion of an array. It takes two parameters, the start index (inclusive) and the end index (exclusive).

2) splice(start, deleteCount, item1, item2, ...):-

const mySplice = myArr.splice(1, 3); // Removes elements from index 1 to 3
  • The splice method changes the contents of an array by removing or replacing existing elements and/or adding new elements.

  • it takes three parameters: the start index, the number of elements to remove, and optional items to add.

  • The key difference is that splice modifies the original array, while slice creating a new array.

  • Additionally, splice returns an array containing the removed elements.

Questioning Arrays:

1) includes(element):-

console.log(myArr.includes(200)); // Output: false
  • The includes method checks if a specific element is present in the array and returns a boolean.

2) indexOf(element):-

console.log(myArr.indexOf(2)); // Output: 1
console.log(myArr.indexOf(10)); // Output: -1
  • The indexOf method returns the index of the first occurrence of a specified element in the array. If the element is not found, it returns -1.

Converting Arrays to Strings:

join(separator):-

const newArr = myArr.join();
console.log(newArr);
  • Arrays can be converted to strings using the join method