JavaScript Array – How to Use Them?
JavaScript arrays are versatile, ordered collections of elements that can hold items of any data type, including numbers, strings, or objects. They offer a range of methods for traversal, manipulation, and searching, making them essential for handling lists and datasets in web development. Arrays in JavaScript are dynamic, allowing elements to be added or removed and their size to change during runtime.
JavaScript Arrays are global objects that store data. An array is a collection or list of zero or more data types and contains numbered indices starting with 0. Arrays are highly helpful because they allow individuals to organize and condense code, making it easier to read and maintain. They do this by storing several values in a single variable. Additionally, JavaScript arrays are capable of holding any data, including objects, characters, and integers. Let's understand this essential JavaScript concept with the help of examples.
Explore Online JavaScript Courses and learn about its essential concepts
Table of Contents
- What is JavaScript Array
- How to Declare Javascript Array?
- Initializing Javascript Array – Different Methods
- How to Access JavaScript Array Elements
- Changing JavaScript Array Element
What is JavaScript Array?
An array is a fundamental data structure used to store a collection of elements. JavaScript array is a special variable that consists of one or more values. A JavaScript Array is a dynamic, high-level, list-like object used to store ordered collections. Elements can be of any type and are accessed by their index. Arrays in JavaScript are mutable, allowing for operations like adding, removing, and altering elements using built-in methods.
Syntax:
const array_name = [“item1”, “item2”, “item3”];
Example:
const colors = [“Black”, “White”, “Blue”];
Explanation:
The above code defines a constant array named 'colors' containing three string elements: "Black", "White", and "Blue". Since the code only declares and initializes the array but doesn't include any operations or commands to display or manipulate the array, there's no output to be shown from this snippet as it stands.
If you want to see the contents of the array displayed, you would need to add a command to do so, such as console.log(colors); which would output the array to the console.
Best-suited Programming courses for you
Learn Programming with these high-rated online courses
Characteristics of JavaScript Array
A Javascript array has the following characteristics:
- JavaScript Array object allows you to store multiple values in a single variable.
- Values of the same or different data types can be used within a JavaScript Array.
- JavaScript arrays use only nonnegative integers as indexes
- The first element in a JavaScript array is at index 0, the second element at index 1, and so on. (Total size: arrayLength – 1)
- 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 increase in 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.
Example:
// 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.
Example:
constcolors = [ "Black", "White", "Blue", "Purple", "Red",];
How to Declare Javascript Array?
The array literal in JavaScript makes it easy to create an array.
Let’s find out how to declare an array using var, const, and let.
Syntax:
var array_name = [item1, item2, …];
Example:
var colors= [“Black”, “White”, “Blue”];
Syntax:
const array_name = [item1, item2, ...];
Example:
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.
Example:
const colors = ["Black", "White", "Blue"];
//Changing an elementcolors[0] = "Pink";
//Adding an elementcolors.push("Green");
Using let
let array_name= [item1, item2, ...];
Example:
let colors = [ “Black” , “White” , “Blue” ];
NOTE: Let is used when the value of the JavaScript array needs to be changed.
Example:
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.
Want to Become a Certified JavaScript Developer? Check these Free Courses and Certifications
Initializing Javascript Array – Different Methods
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: array literal syntax and Array constructor syntax.
- Array Literal
An array literal is a list of elements present within square brackets in an array. 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.
Syntax:
const <array-name> = [element0, element1, element2,... elementN];
Example: Declare and initialize a JavaScript Array
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];
NOTE: JavaScript array can include constant elements of same or different data types.
- Array Constructor
The JavaScript Array constructor method returns the constructor function of an array object. This method only returns the reference of the function and not the functions’ name. Hence, JavaScript arrays return the function Array() [[native code]]. Moreover, in this method, you can initialize an array with an Array constructor syntax, a new keyword.
It is possible to display array constructors in three different ways:
Syntax:
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.
Example:
conststringArray = new Array();stringArray[0] = "one";stringArray[1] = "two";stringArray[2] = "three";stringArray[3] = "four";
const numericArray = new Array(3);numericArray[0] = 1;numericArray[1] = 2;numericArray[2] = 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
Name/value pairs are not present in arrays.Their indexes begin with 0 rather than with a decimal number. As an example, we show a color array. Square brackets enclosed in JavaScript arrays denote the index numbers of items.
Example:
let colors = [ "black", "white", "blue", "purple", "red",];
In the following table you can see the index array for each element in the colors array.
Black | White | Blue | Purple | Red |
0 | 1 | 2 | 3 | 4 |
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.
Example:
colors[1];
Output:
white
Changing JavaScript Array Element
Adding an Item to JavaScript Array
In our color, we had five items, whose indices ranged 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.
Example:
colors[5] = "pink";
colors;
Output:
[ 'black', 'white', 'blue', 'purple', 'red', 'pink' ]
NOTE: The array will become undefined if we add an item and accidentally skip an index.
Example:
colors[7] = "yellow";
Output:
[ 'black', 'white', 'blue', 'purple', 'red', 'pink' , 'yellow' ]
An attempt to access the extra array item will return undefined.
Example:
colors[6]
Output:
undefined
As a result, such issues can be managed using the push() method, which includes adding an element to the end of an array.
Example:
// Append green to the end of the colors array
colors.push("green");
colors;
Output:
Output ['black', 'white', 'blue', 'purple', 'red', 'pink' , 'yellow' ‘green’ ]
On the other hand, the unshift() method adds an element to the beginning of an array.
Example:
// Append orange to the beginning of the colors array
colors.unshift("orange");
colors
Output:
[ 'orange', ['black', 'white', 'blue', 'purple', 'red', 'pink' , 'yellow' 'green’ ]
In the above examples, we have push() and unshift(), two JavaScript array methods used to append items to the start and end of an array.
Removing an Item from JavaScript Array
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.
Example:
colors.splice(7, 1);
colors;
Output:
[‘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.
Modifying Items in JavaScript Array
Example:
// Assign brown to the first item in the color array
colors[0] = "brown";
colors;
Output:
[ '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.
Example:
// blue with peach using splice method
colors.splice(3, 1, "peach");
colors();
Output:
[ '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.
Prepare for your next Javascript interview – Most Asked Javascript Interview Questions
Wrapping It Up!!
Arrays are fundamental, essential, and versatile part of programming in JavaScript. In the above blog, we have covered what Array is, why we use it, and how to declare and initialize an array in Javascript. Also, topics such as how to access and change an array element, i.e, creating, removing, and modifying items along with its different operations, have been explained.
Top FAQs on JavaScript Array
What is a JavaScript Array?
A JavaScript array is an ordered collection of items, which can be of different data types like strings, numbers, or objects. Arrays are used to store multiple values in a single variable.
How do you create an Array in JavaScript?
You can create an array using square brackets []. For example, let fruits = ["apple", "banana", "mango"];.
How do you add an item to an Array?
You can add an item using the push() method for adding to the end, or unshift() for adding to the beginning. For example, fruits.push("orange");.
How do you remove an item from an Array?
Use pop() to remove the last item or shift() to remove the first item. You can also use splice() to remove items at a specific index.
How do you access an item in an Array?
Access items by their index, starting with 0. For example, fruits[0] will access the first item, "apple".
Chanchal is a creative and enthusiastic content creator who enjoys writing research-driven, audience-specific and engaging content. Her curiosity for learning and exploring makes her a suitable writer for a variety ... Read Full Bio