Table of Contents
const array_name = [“item1”, “item2”, “item3”];
const colors = [“Black”, “White”, “Blue”];
- An array can contain values of mixed types. For example, you can have an array that includes elements with string types, numbers, boolean, and null.
- An array is dynamic and can have an increasing size. In other words, defining the array size in advance is not necessary.
Consider assigning the five colors to their own items to demonstrate how arrays can be useful.
// Assign the five colors to five itemslet color1 = "Black";let color2 = "White";let color3 = "Blue";let color4 = "Purple";let color5 = "Red";
Therefore, due to its verbosity, it is tough to track and maintain.
We can organize our data with the help of arrays.
constcolors = ["Black","White","Blue","Purple","Red",];
Let’s find out how to declare an array using var, const, and let.
var array_name = [item1, item2, …];
var colors= [“Black”, “White”, “Blue”];
const array_name = [item1, item2, ...];
const colors = [ “Black” , “White” , “Blue” ];
We commonly declare an array with a const keyword.
NOTE: Use const when you want to keep your array fixed and constant/unchanged.
const colors = [ “Black” , “White” , “Blue” ];const colors =[ “Pink” , “White” , “Green” ]; // Error
We cannot change the element of the constant array.
const colors = ["Black", "White", "Blue"];//Changing an elementcolors = "Pink";//Adding an elementcolors.push("Green");
let array_name= [item1, item2, ...];
let colors = [ “Black” , “White” , “Blue” ];
const price1= 7;const price2= 8;let total= price1 + price2;
Here, in the above example, price1 and price2 are declared using the const keyword as their values are constant and cannot be changed.
Variable total is declared with the let keyword as its value can be changed.
A comma-separated set of constant expressions encased in braces () serves as an array’s initializer. You can put an equal sign (=) in front of the initializer.It is not necessary to initialize every element in an array. Hence, if an array is partially initialized, the value 0 of the proper type is assigned to any uninitialized items.
There are two ways to define and initialize an array in two ways, array literal and Array constructor syntax.
- Array Literal
A list of elements present within square brackets in an array is known as Array Literals. When you create an array using an array literal, its length is set to the number of arguments supplied and its components are initialized with the specified values.
const <array-name> = [element0, element1, element2,... elementN];
const stringArray = ["one", "two", "three"];const numericArray = [1, 2, 3, 4];const decimalArray = [1.1, 1.2, 1.3];const booleanArray = [true, false, false, true];const mixedArray = [1, "two", "three", 4];
- Array Constructor
It is possible to display array constructors in three different ways:
const arrayName = new Array();const arrayName = new Array(Number length);const arrayName = new Array(element1, element2, element3,... elementN);
As shown in the above syntax, an array can be initialized using a new keyword in the same way as an object.
The following example demonstrates how to define an array using the Array constructor syntax.
conststringArray = new Array();stringArray = "one";stringArray = "two";stringArray = "three";stringArray = "four";const numericArray = new Array(3);numericArray = 1;numericArray = 2;numericArray = 3;const mixedArray = new Array(1, "two", 3, "four");
NOTE: An array can only have a numeric index (key). The index cannot be of string or any other data type. The following syntax is incorrect.
Example: Incorrect Array Index
const stringArray = new Array();stringArray["one"] = "one";stringArray["two"] = "two";stringArray["three"] = "three";stringArray["four"] = "four";
How to Access Array Elements
Indexing an Array
let colors = ["black","white","blue","purple","red",];
In the following table you can see the index array for each element in the colors array.
The first item in the array is Black, which is indexed at 0. The last item is Red, which is indexed at 4. In an array, index begins at 0 and ends at (array_length – 1).
Accessing an Array
You can access array elements by specifying their index number within square brackets.
In our color we had five items, which consisted of the indices from 0 to 4. So, if we want to add a new item to the array, we can assign a value to the next index.
colors = "pink";colors;
[ 'black', 'white', 'blue', 'purple', 'red', 'pink' ]
NOTE: The array will become undefined if we add an item and accidentally skip an index.
colors = "yellow";
[ 'black','white','blue','purple','red','pink','yellow' ]
An attempt to access the extra array item will return undefined.
As a result, such kind of issues can be managed by using the push() method, which include an element to the end of an array.
// Append green to the end of the colors array
Output ['black', 'white', 'blue', 'purple', 'red', 'pink' , 'yellow' ‘green’ ]
On the other hand, if you use the unshift() method, it will add an element to the beginning of an array.
// Append orange to the beginning of the colors array
[ 'orange', ['black', 'white', 'blue', 'purple', 'red', 'pink' , 'yellow' 'green’ ]
The splice() technique eliminates a specific item from an array. Let’s remove the previously undefined array item we unintentionally added to the colors array.
[‘orange’ 'black', 'white', 'blue', 'purple', 'red', 'pink' 'yellow' ‘green’]
Splice() will modify the original item. Use splice() and assign the result to a new item if you want the original variable to stay the same. Here, we’ll assign two items: one that uses splice() to hold the colors array up till the pink element and another that stores the yellow and green items.
// Assign brown to the first item in the color array
colors = "brown";colors;
[ 'brown', 'black', 'white', 'blue', 'purple', 'red', 'pink' ]
Using the splice() method with a new parameter is an additional technique of changing a value. As a result, blue, the item at index 3, might be deleted and a new item added instead, if we want to alter its value.
// blue with peach using splice method
colors.splice(3, 1, "peach");colors();
[ 'brown', 'black', 'white', 'peach', 'purple', 'red', 'pink' ]
Therefore, in the aforementioned illustration, blue was removed from the array, while index 3 was replaced with a new value.
Wrapping It Up!!
Download this article as PDF to read offlineDownload as PDF