JavaScript Arrays, Working with Lists of Data

Java Script @ Freshers.in

In this article, we’ll explore JavaScript arrays, covering the basics, key methods, and providing real-world examples to help you harness the full potential of arrays in your coding journey.

JavaScript Arrays at a Glance

Arrays in JavaScript are ordered collections of values, where each value is identified by an index. Arrays can hold various data types, including numbers, strings, objects, and even other arrays. They offer flexibility and efficiency for tasks involving multiple items.

Key Topics Covered:

  1. Creating Arrays: Learn how to create arrays using array literals and constructors.
  2. Accessing Elements: Explore methods to access array elements by index and understand zero-based indexing.
  3. Modifying Arrays: Discover ways to add, remove, and modify elements within an array.
  4. Iterating Through Arrays: Master different methods for looping through array elements.
  5. Array Methods: Explore built-in array methods for sorting, filtering, mapping, and more.
  6. Multi-dimensional Arrays: Understand how to work with arrays of arrays for complex data structures.

Examples to Illuminate Concepts

Let’s dive into real-world examples to illustrate key concepts related to JavaScript arrays:

Example 1: Creating and Accessing Arrays

const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // Output: 'apple'
console.log(fruits[2]); // Output: 'cherry'

Here, we create an array of fruits and access its elements by index.

Example 2: Modifying Arrays

const colors = ['red', 'green', 'blue'];
colors.push('yellow'); // Add an element to the end
colors.pop(); // Remove the last element
colors[1] = 'orange'; // Modify an element
console.log(colors); // Output: ['red', 'orange', 'blue']

In this example, we demonstrate adding, removing, and modifying array elements.

Example 3: Iterating Through Arrays

const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

We use a for loop to iterate through array elements and print them.

Example 4: Using Array Methods

const temperatures = [18, 25, 30, 22, 27];
const hotDays = temperatures.filter(temp => temp > 25);
console.log(hotDays); // Output: [30, 27]

Here, we employ the filter() method to create a new array containing temperatures above 25 degrees.

Author: user