Advertisement

Responsive Advertisement

Array and array methods in JavaScript

Introduction

Arrays are one of the most commonly used data structures in JavaScript. They allow us to store and manipulate collections of data, such as numbers, strings, or objects, in a single variable. In this post, we'll cover the basics of arrays and some of the most commonly used array methods.



Creating Arrays

To create an array in JavaScript, you can use square brackets to enclose a comma-separated list of values:

let numbers = [1, 2, 3, 4, 5]; let fruits = ["apple", "banana", "orange"]; let mixed = [1, "apple", true, {}];

Arrays in JavaScript are dynamic, which means that you can add or remove elements from them at any time:

let numbers = [1, 2, 3]; numbers.push(4); // add an element to the end of the array numbers.pop(); // remove the last element from the array


Accessing Array Elements

You can access individual elements of an array by their index, which starts at 0:

let numbers = [1, 2, 3]; console.log(numbers[0]); // 1 console.log(numbers[1]); // 2 console.log(numbers[2]); // 3

You can also use negative indexes to access elements from the end of the array:

let numbers = [1, 2, 3]; console.log(numbers[-1]); // undefined console.log(numbers[-2]); // undefined console.log(numbers[numbers.length - 1]); // 3

Array Methods

JavaScript provides a number of built-in array methods that make it easy to manipulate arrays. Here are some of the most commonly used methods:

  1. push() and pop(): Add and remove elements from the end of an array:
let numbers = [1, 2, 3]; numbers.push(4); // [1, 2, 3, 4] numbers.pop(); // [1, 2, 3]

  1. shift() and unshift(): Add and remove elements from the beginning of an array:
let numbers = [1, 2, 3]; numbers.unshift(0); // [0, 1, 2, 3] numbers.shift(); // [1, 2, 3]
  1. splice(): Add or remove elements from an array at a specific index:
let numbers = [1, 2, 3]; numbers.splice(1, 1); // remove the element at index 1 numbers.splice(1, 0, 4); // insert 4 at index 1
  1. forEach(): Execute a function for each element in an array:
let numbers = [1, 2, 3]; numbers.forEach(function(number) { console.log(number); });
  1. map(): Create a new array by applying a function to each element in an existing array:
let numbers = [1, 2, 3]; let doubled = numbers.map(function(number) { return number * 2; });
  1. filter(): Create a new array that contains only elements that pass a certain test:
let numbers = [1, 2,3, 4, 5];
let evenNumbers = numbers.filter(function(number) { return number % 2 === 0; });

8. reduce(): Reduce an array to a single value by applying a function to each element and accumulating the result:

let numbers = [1, 2, 3]; let sum = numbers.reduce(function(total, number) { return total + number; }, 0);

Post a Comment

0 Comments