What is Array in Javascript

In this blog, we’ll explore arrays in JavaScript, covering their definition, creation, manipulation, and common use cases. We’ll understand Elements in an Array, Indexing of array elements, Creating arrays and assigning values to their elements, Creating and initializing arrays in a single statement, and Displaying the contents of arrays, Array length, and Types of values in array elements.

What is Array in Javascript?

Arrays are fundamental data structures in Javascript used to store a collection of values under a single variable name. They provide an organized and efficient way to manage related data elements. In the context of JavaScript, arrays are commonly used to hold various types of values such as numbers, strings, objects, or even other arrays.

Definition of Array

An array is a structured layout of data where elements are organized in a table-like format. You can access specific values by using the array name along with a numeric index that points to the corresponding position in the table. Using a loop with a numeric variable allows efficient operations on all or a specific range of values within the array.

Array in Javascript Examples

Example: Storing Names of Animals

Let’s consider a practical scenario: you want to store the names of the names of the animals. Instead of creating 4 separate variables to store each animal’s name, you can use an array to manage this data efficiently. Let’s check below how you can create an array to store the names of the animals:

// Create an array to store animals
const animals = ['Tiger', 'Rabbit', 'Lion', 'Monkey'];

Get a Complete list of Online Certification Courses in India here!

In this example, we’ve defined an array called `animals` using square brackets `[]`. Inside the brackets, we list the names of the animals as strings, separated by commas. Each element in the array is a value – in this case, an animal’s name.

Element in Array

An “element” within an array refers to an individual value or data entry stored within the array structure. For instance, considering an array that holds the names of the 4 animals, each animal’s name (such as “Tiger,” “Rabbit,” etc.) is an element of that array. Elements are accessed and manipulated using their corresponding positions or indices within the array.

Indexing of array elements 

In the realm of array manipulation, indexing involves the assignment of a distinct numerical label to each element contained within the array. To illustrate this concept, consider an array dubbed “animals,” wherein “Lion” occupies index 0, “Tiger” resides at index 1, and so forth. This numerical identifier acts as a compass to precisely pinpoint particular animals and execute various operations involving them. For instance, referencing “animals[2]” would yield the value “Elephant.” This methodical indexing mechanism streamlines the retrieval and manipulation of data, facilitating efficient interactions with specific array elements based on their designated positions. As a result, it fosters an orderly and fluid approach to programming tasks, enhancing both organization and efficacy.

Creating arrays and assigning values to their elements

Creating arrays involves declaring a variable with square brackets, specifying the number of elements, or directly providing values. For instance, to store the 4 animals as strings:

// Create an array to store animals
const animals = new Array(4);
animals[0] = 'Tiger';
animals[1] = 'Rabbit';
animals[2] = 'Lion';
animals[3] = 'Monkey';

Creating and initializing arrays in a single statement 

one-liner code mentioned below for creating and initializing the array to store the 4 animals:

const animals = ['Tiger', 'Rabbit', 'Lion', 'Monkey'];

In this concise line of code, the `animals` array is created and simultaneously populated with the animal names “Tiger,” “Rabbit,” “Lion,” and “Monkey,” each element separated by commas within the array literal. This approach efficiently combines array creation and initialization into a single statement.

This single statement combines the declaration of a new variable and Array object with assigning the four animals Strings. Notice that we have not had to specify the size of the array, since JavaScript knows there are seven Strings and so makes the array have a size of four elements. 

The above examples illustrate that arrays can either be created separately (as in VERSION 1), and then have values assigned to elements, or that arrays can be created and provided with initial values all in one statement (VERSION 2). 

When declaring the array, if you know which values the array should hold you would likely choose to create the array and provide the initial values in one statement. Otherwise the two-stage approach of first creating the array, and then later assigning the values, is appropriate.

Check out Javascript for Loop, Now!

Displaying the contents of arrays 

The easiest way to display the contents of an array is to simply use the document.write() function. This function, when given an array name as an argument, will display each element of the array on the same line, separated by commas. For example, the code: 

var Animals = new Array( "Tiger", "Rabbit", "Lion", "Monkey"); 
document.write( " Animals: " + Animals);

Output:

Animals: Tiger,Rabbit,Lion,Monkey

Array length 

The term length, rather than size, is used to refer to the number of elements in the array. The reason for this will become clear shortly. As illustrated in the VERSION 1 code above, the size of an array can be specified when an array is declared:

var Animals = new Array(4);

This creates an array with seven elements (each containing an undefined value):

IndexValue
Animals[0]<undefined>
Animals[1]<undefined>
Animals[2]<undefined>
Animals[3]<undefined>

In fact, while this is good programming practice, it is not a requirement of the JavaScript language. The line written without the array size is just as acceptable to JavaScript: 

var Animals= new Array();

this creates an array, with no elements:

IndexValue

In this second case, JavaScript will make appropriate changes to its memory organization later, once it identifies how many elements the array needs to hold. Even then, JavaScript can extend the size of an array to contain more elements than it was originally defined to contain. 

For example, if we next have the statement: 

Animals[3] = "Monkey";

the JavaScript interpreter will identify the need for the Animals array to have at least four elements, and for which the 4th element is the String “Monkey”.

IndexValue
Animals[0]<undefined>
Animals[1]<undefined>
Animals[2]<undefined>
Animals[3]“Monkey”

The length of each of these arrays is as follows: 

• weekDays.length = 4

• months.length = 0 

• bits.length = 3 
One needs to be careful, though, since making the length of an array smaller can result in losing some elements irretrievably. Consider this code and the following output:

var bits = new Array('Tiger', 'Rabbit', 'Lion', 'Monkey');
document.write(bits);
document.write("array length: " + bits.length);
bits.length = 2;
document.write("after change:");
document.write(bits);
document.write("array length: " + bits.length);

Learn How to Generate Random Numbers in Javascript, Now!

Output:

As can be seen, after the statement bits.length = 4; the last two array elements have been lost

[ 'Tiger', 'Rabbit', 'Lion', 'Monkey' ]
array length: 4
after change:
[ 'Tiger', 'Rabbit' ]
array length: 2

Types of values in array elements 

In most high-level programming languages arrays are typed. This means that when an array is created the programmer must specify the type of the value to be stored in the array. With such languages, all elements of an array store values of a single type. However, JavaScript is not a strongly typed programming language, and a feature of JavaScript arrays is that a single array can store values of different types. Consider the following code:

var things = new Array();
things[0] = "Newtum";
things[1] = "85";
things[2] = false;
document.write("[0]: " + things[0]);
document.write("[1]: "+ things[1]);
document.write("[2]: " + things[2]);

As can be seen, this is perfectly acceptable JavaScript programming:

Output:

[0]: Newtum
[1]: 85
[2]: false

When the value of an array element is replaced with a different value, there is no requirement for the replacement value to be of the same type. In the example below, array element 1 begins with the String “hello”, is then changed to the Boolean value false, and changed again to the number 3.1415:

var things = new Array();
things[0] = 21;
things[1] = "hello";
things[2] = true;
things[1] = false;
things[1] = 3.1415;
document.write("[0]: " + things[0]);
document.write("[1]: " + things[1]);
document.write("[2]: " + things[2]);

Output:

[0]: 21
[1]: 3.1415
[2]: true

We can confirm that a single array can store values of different types by displaying the return value of the typeof function: 

var things = new Array();
things[0] = 58;
things[1] = "hello";
things[2] = true;
document.write("type of things[0]:" + typeof things[0] );
document.write("type of things[1]: " + typeof things[1] );
document.write("type of things[2]: " + typeof things[2] );

Output:

type of things[0]:number
type of things[1]: string
type of things[2]: boolean

In the world of JavaScript, arrays emerge as indispensable tools for data organization and manipulation. They simplify coding by offering a systematic approach to group and manage values. Through dynamic indexing and flexible initialization, arrays prove their efficiency in accommodating diverse data types. As you explore JavaScript’s array of capabilities, you unlock the potential for streamlined and structured programming, propelling your coding endeavors to new heights.

We hope that our blog on ‘What is Array in Javascript’ helps you. You can also visit our Newtum website for more information on various courses and blogs about  PHP, C Programming for kids, Java, and more. Happy coding with Newtum!

About The Author

Leave a Reply