Arrays in JavaScript

Introduction Link to heading

An array in JavaScript is an object that allows you to store a collection of values of any type (numbers, strings, objects, etc.) in an organized and accessible way.

Array creation Link to heading

  • You can create an array using [] square brackets and separating the values with commas.

Example Link to heading

const fruits = ["Apple", "Banana", "Cherry", "Strawberry"];

Access to elements Link to heading

  • You can access a specific element of the array using its index in square brackets.
  • The index starts at 0, so the first element has index 0, the second has index 1, and so on.

Example Link to heading

console.log(fruits[0]); // Prints "Apple"
console.log(fruits[2]); // Prints "Cherry"

Properties and methods Link to heading

  • Arrays have properties and methods that allow you to manipulate their contents.

Properties Link to heading

  • length Tells you the length of the array (the number of elements it contains).

Methods Link to heading

  • push(): Adds one or more elements to the end of the array.
  • pop(): Removes the last element from the array.
  • unshift(): Adds one or more elements to the beginning of the array.
  • shift(): Delete the first element of the array.
  • indexOf(): Searches for an element in the array and returns its index.
  • filter(): Creates a new array with the elements that meet a condition.
  • map(): Creates a new array with the results of applying a function to each element of the original array.
  • find(): Searches for an element in the array and returns the first element that meets a condition.
  • forEach(): Loop through each element of the array and execute a function for each one.

Method examples Link to heading

const fruits = ["Apple", "Banana", "Cherry", "Strawberry"];

// Add an element to the end of the array
fruits.push("Grapes");

// Remove the last element from the array
fruits.pop();

// Add an element to the beginning of the array
fruits.unshift("Grapes");

// Remove the first element from the array
fruits.shift();

// Find the position of an element
const position = fruits.indexOf("Cherry");

const articles = [
  { name: "Bike", cost: 3000 },
  { name: "Tv", cost: 2500 },
  { name: "Book", cost: 320 },
  { name: "Cellphone", cost: 10000 },
  { name: "Laptop", cost: 20000 },
  { name: "keyboard", cost: 500 },
  { name: "Headphones", cost: 1700 },
];

// Filter elements
const filteredItems = items.filter(function (item) {
  return item.cost <= 500;
});

// Get the names of the items
const itemNames = items.map(function (item) {
  return item.name;
});

// Find an item by name
const foundItem = items.find(function (item) {
  return item.name === "Laptop";
});

// Iterate over the array and print the names
items.forEach(function (item) {
  console.log(item.name);
});

Keep learning about arrays to write more organized and efficient JavaScript code!

<< Operators in JavaScript Objects in JavaScript >>