Arrays in JavaScript are a way to store multiple values in a single variable. They are incredibly useful for handling lists or collections of data. In this tutorial, we'll explore arrays using examples related to blockchain and cryptocurrencies.
Creating an Array
To create an array, you can use square brackets []
. Each item in the array is separated by a comma.
let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano"];
console.log(cryptocurrencies); // Outputs: ["Bitcoin", "Ethereum", "Cardano"]
// or let cryptocurrencies = new Array ("Bitcoin", "Ethereum", "Cardano");
Array Type Checking
To check if a variable is an array
console.log(Array.isArray(cryptocurrencies)); // true
Length
The length property returns the number of elements in an array.
console.log(cryptocurrencies.length); // 3
Accessing Array Elements
You can access an element in an array by referring to its index number. Array indexes start from 0.
console.log(cryptocurrencies[0]); // Outputs: Bitcoin
indexOf
Finds the index of an element in the array.
let index = cryptocurrencies.indexOf("Ethereum");
console.log(index); // 1
Modifying an Array
You can modify an existing array by accessing an index and assigning a new value.
cryptocurrencies[2] = "Solana";
console.log(cryptocurrencies); // Outputs: ["Bitcoin", "Ethereum", "Solana"]
Adding Elements to an Array
JavaScript arrays have various methods to add new elements. push()
adds an element at the end of the array.
cryptocurrencies.push("Litecoin");
console.log(cryptocurrencies); // Outputs: ["Bitcoin", "Ethereum", "Solana", "Litecoin"]
unshift()
adds an element at the start of the array
cryptocurrencies.unshift("Cardano");
console.log(cryptocurrencies); // ["Cardano", "Bitcoin", "Ethereum", "Solana", "Litecoin"]
Removing Elements from an Array
The pop()
method removes the last element from an array.
let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
cryptocurrencies.pop();
console.log(cryptocurrencies); // Outputs: ["Bitcoin", "Ethereum", "Cardano"]
shift()
Removes the first element from an array.
cryptocurrencies.shift(); // Removes "Bitcoin"
// Outputs: ["Ethereum", "Cardano"]
Creating new array from another
slice()
Returns a new array containing a portion of the original array.
let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
console.log(cryptocurrencies.slice(0, 2));
// Array["Bitcoin", "Ethereum"]
console.log(cryptocurrencies.slice(1, 3));
// Expected output: Array["Ethereum", "Cardano"]
Changing Contents Of An Array
splice()
method of Array instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
// Inserts at index 1
cryptocurrencies.splice(1, 0, "Binance");
console.log(cryptocurrencies)
// Array["Bitcoin", "Binance", "Ethereum", "Cardano", "Solana"]
// Replaces 1 element at index 4
cryptocurrencies.splice(4, 1, "Dogecoin");
console.log(cryptocurrencies)
// Expected output: Array["Bitcoin", "Binance", "Ethereum", "Cardano", "Dogecoin"]
Iterating Over Arrays
You can loop over an array using a for
loop or forEach
method.
Example with for
loop:
let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
for(let i = 0; i < cryptocurrencies.length; i++) {
console.log(cryptocurrencies[i]);
// Expected outputs in order: "Bitcoin", "Ethereum", "Cardano", "Solana"
}
Example with forEach
:
cryptocurrencies.forEach(crypto => {
console.log(crypto);
// Expected outputs in order: "Bitcoin", "Ethereum", "Cardano", "Solana"
});
Example with map
:
let lengths = cryptocurrencies.map(function(item) {
return item.length;
});
console.log(lengths); // [7, 8, 7, 6]
filter()
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers); // [2, 4, 6]
reduce()
The reduce()
method executes a reducer function on each element of the array, resulting in a single output value.
Syntax
let result = array.reduce(function(accumulator, currentValue, currentIndex, array) {
// return result from performing operation
}, initialValue);
*accumulator: Accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied.
*currentValue: The current element being processed in the array.
*currentIndex (optional): The index of the current element being processed in the array.
*array (optional): The array reduce was called upon.
*initialValue (optional): A value to use as the first argument to the first call of the callback.
The sum of all numbers in an array:
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // 15
Spread Operator
Combine two arrays
let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
let numbers = [1, 2, 3, 4, 5, 6]
let combined = [...cryptocurrencies, ...numbers];
console.log(combined); // ["Bitcoin", "Ethereum", "Cardano", "Solana", 1, 2, 3, 4, 5, 6]
Converting Arrays To Strings Using join()
let currencyString = cryptocurrencies.join(", ");
console.log(currencyString); // "Bitcoin", "Ethereum", "Cardano", "Solana"
Practical Exercise
- Create an array named
blockchains
with elements "Ethereum", "Binance Smart Chain", and "Cardano". - Add "Polkadot" to the end of the
blockchains
array. - Replace "Binance Smart Chain" with "Solana".
- Use a loop to print each element of the
blockchains
array.
Arrays are a fundamental part of JavaScript and mastering them is crucial for any aspiring developer. So remember to practise.
Did I miss out any knowledge about Arrays? Let me know in the comments. Thanks.
Top comments (0)