Dear readers, here I am for another weekly article on JavaScript.
This week, I begin to cover data structures in JavaScript, which are a very important concept in other programming languages, as well.
Understanding Arrays
An array in JavaScript is a fundamental data structure that stores multiple values, or elements, in a single variable. Think of it as an ordered list, where each item has a specific position, or index, starting from 0. Arrays are incredibly versatile and are used extensively in JavaScript programming for a variety of tasks.
Key Characteristics:
Ordered: Elements have a defined order, accessible by their index.
Mutable: Elements can be changed after creation.
Dynamic: The size of an array can change as elements are added or removed.
Heterogeneous: Elements can be of different data types (numbers, strings, objects, even other arrays).
Creating Arrays
There are two primary methods for creating arrays:
1. Array Literal
The most common and concise way to create an array is using an array literal:
const fruits = ["apple", "banana", "orange"];
This syntax creates an array named fruits containing three string elements.
2. Array Constructor
While less common, the Array constructor can also be used:
const numbers = new Array(5); // Creates an array with 5 empty elements
This creates an array named numbers with a length of 5, but initially filled with undefined values.
Accessing and Modifying Array Elements
To access an element, you use its index within square brackets:
const colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: "red"
To modify an element, assign a new value to its index:
colors[1] = "yellow";
console.log(colors); // Output: ["red", "yellow", "blue"]
Array Length
The length property of an array indicates the number of elements it contains:
console.log(colors.length); // Output: 3
Array Methods
JavaScript provides a rich set of built-in methods for manipulating arrays. Let's delve into some of the most commonly used ones:
Adding Elements
push(element1, ..., elementN): Adds one or more elements to the end of the array and returns the new length.
const numbers = [1, 2, 3];
numbers.push(4, 5); // numbers is now [1, 2, 3, 4, 5]
unshift(element1, ..., elementN): Adds one or more elements to the beginning of the array and returns the new length.
const colors = ["red", "green"];
colors.unshift("blue"); // colors is now ["blue", "red", "green"]
Removing Elements
pop(): Removes and returns the last element of the array.
const fruits = ["apple", "banana", "orange"];
const removedFruit = fruits.pop(); // removedFruit is "orange", fruits is ["apple", "banana"]
shift(): Removes and returns the first element of the array.
const colors = ["red", "green", "blue"];
const removedColor = colors.shift(); // removedColor is "red", colors is ["green", "blue"]
splice(start, deleteCount, item1, ..., itemN): Removes or replaces elements at specific positions.
const numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 1, 10); // numbers is now [1, 2, 10, 4, 5]
Searching and Finding Elements
indexOf(searchElement, fromIndex): Returns the index of the first occurrence of a specified value, or -1 if not found.
const fruits = ["apple", "banana", "orange"];
const index = fruits.indexOf("banana"); // index is 1
lastIndexOf(searchElement, fromIndex): Returns the index of the last occurrence of a specified value, or -1 if not found.
includes(searchElement, fromIndex): Returns true if an array contains a specified value, otherwise false.
const numbers = [1, 2, 3, 4, 5];
const found = numbers.includes(3); // found is true
Iterating Over Arrays
forEach(callback(currentValue, index, array)): Executes a provided function once for each array element.
const numbers = [1, 2, 3];
numbers.forEach(number => console.log(number));
map(callback(currentValue, index, array)): Creates a new array by applying a function to each element.
const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(number => number * 2);
filter(callback(currentValue, index, array)): Creates a new array with elements that pass a test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(number => number % 2 === 0);
reduce(callback(accumulator, currentValue, index, array), initialValue): Reduces an array to a single value.
const numbers = [1, 2, 3];
const sum = numbers.reduce((total, number) => total + number, 0);
Multidimensional Arrays
Arrays can contain other arrays, creating multidimensional arrays:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Common Use Cases for Arrays
Storing lists of items (e.g., shopping lists, to-do lists)
Handling tabular data (e.g., spreadsheets)
Creating matrices for mathematical operations
Implementing data structures like stacks and queues
This is it for this week’s article folks, hope you will all have a nice weekend and till next week, happy coding!