JavaScript Arrays (original) (raw)

In JavaScript, an array is an ordered list of values. Each value is called an element, and each element has a numeric position in the array, known as its index. Arrays in JavaScript are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.

JavaScript-Array

Array in JavaScript

Why Use Arrays?

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

let car1 = "Saab"
let car2 = "Volvo"
let car3 ="BMW"

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

**1. Create Array using Literal

Creating an array using array literal involves using square brackets [] to define and initialize the array.

JavaScript `

// Creating an Empty Array let a = []; console.log(a);

// Creating an Array and Initializing with Values let b = [10, 20, 30]; console.log(b);

`

**2. Create using new Keyword (Constructor)

The "**Array Constructor" refers to a method of creating arrays by invoking the Array constructor function.

javascript `

// Creating and Initializing an array with values let a = new Array(10, 20, 30);

console.log(a);

`

**Note: Both the above methods do exactly the same. Use the array literal method for efficiency, readability, and speed.

**Recommended Links

Basic Operations on JavaScript Arrays

**1. Accessing Elements of an Array

Any element in the array can be accessed using the index number. The index in the arrays starts with 0.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"];

// Accessing Array Elements console.log(a[0]); console.log(a[1]);

`

2. Accessing the First Element of an Array

The array indexing starts from 0, so we can access first element of array using the index number.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"];

// Accessing First Array Elements let fst = a[0];

console.log("First Item: ", fst);

`

3. Accessing the Last Element of an Array

We can access the last array element using [array.length - 1] index number.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"];

// Accessing Last Array Elements let lst = a[a.length - 1];

console.log("First Item: ", lst);

`

**4. Modifying the Array Elements

Elements in an array can be modified by assigning a new value to their corresponding index.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; console.log(a);

a[1]= "Bootstrap"; console.log(a);

`

Output

[ 'HTML', 'CSS', 'JS' ] [ 'HTML', 'Bootstrap', 'JS' ]

5. Adding Elements to the Array

Elements can be added to the array using methods like push() and unshift().

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"];

// Add Element to the end of Array a.push("Node.js");

// Add Element to the beginning a.unshift("Web Development");

console.log(a);

`

Output

[ 'Web Development', 'HTML', 'CSS', 'JS', 'Node.js' ]

6. Removing Elements from an Array

To remove the elements from an array we have different methods like pop(), shift(), or splice().

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; console.log("Original Array: " + a);

// Removes and returns the last element let lst = a.pop(); console.log("After Removing the last: " + a);

// Removes and returns the first element let fst = a.shift(); console.log("After Removing the First: " + a);

// Removes 2 elements starting from index 1 a.splice(1, 2); console.log("After Removing 2 elements starting from index 1: " + a);

`

Output

Original Array: HTML,CSS,JS After Removing the last: HTML,CSS After Removing the First: CSS After Removing 2 elements starting from index 1: CSS

7. Array Length

We can get the length of the array using the array length property.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"];

let len = a.length;

console.log("Array Length: " + len);

`

8. Increase and Decrease the Array Length

We can increase and decrease the array length using the JavaScript length property.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]

// Increase the array length to 7 a.length = 7;

console.log("After Increasing Length: ", a);

// Decrease the array length to 2 a.length = 2; console.log("After Decreasing Length: ", a)

`

Output

After Increasing Length: [ 'HTML', 'CSS', 'JS', <4 empty items> ] After Decreasing Length: [ 'HTML', 'CSS' ]

9. Iterating Through Array Elements

We can iterate array and access array elements using for loop and forEach loop.

**Example: It is an example of for loop.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"];

// Iterating through for loop for (let i = 0; i < a.length; i++) { console.log(a[i]) }

`

**Example: It is the example of Array.forEach() loop.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"];

// Iterating through forEach loop a.forEach(function myfunc(x) { console.log(x); });

`

10. Array Concatenation

Combine two or more arrays using the concat() method. It returns new array containing joined arrays elements.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS", "React"]; let b = ["Node.js", "Expess.js"];

// Concatenate both arrays let concateArray = a.concat(b);

console.log("Concatenated Array: ", concateArray);

`

Output

Concatenated Array: [ 'HTML', 'CSS', 'JS', 'React', 'Node.js', 'Expess.js' ]

**11. Conversion of an Array to String

We have a builtin method **toString() to converts an array to a string.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"];

// Convert array ot String console.log(a.toString());

`

12. Check the Type of an Arrays

The JavaScript typeof operator is used ot check the type of an array. It returns "object" for arrays.

JavaScript `

// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"];

// Check type of array console.log(typeof a);

`

**Recognizing a JavaScript Array

There are two methods by which we can recognize a JavaScript array:

Below is an example showing both approaches:

JavaScript `

const courses = ["HTML", "CSS", "Javascript"]; console.log("Using Array.isArray() method: ", Array.isArray(courses)) console.log("Using instanceof method: ", courses instanceof Array)

`

Output

Using Array.isArray() method: true Using instanceof method: true

**Note: A common error is faced while writing the arrays:

const a = [5]
// and
const a = new Array(5)

The above two statements are not the same.

**Output: This statement creates an array with an element " [5] ". Try with the following examples

JavaScript `

// Example 1 const a1 = [5] console.log(a1)

// Example 2 const a2 = new Array(5) console.log(a2)

`

Output

[ 5 ] [ <5 empty items> ]

Apart from these get the complete list of Array Methods by following the Article - JavaScript Array Methods

Basic Problems on Array in JavaScript

**Easy Problems on Array in JavaScript

**Medium Problems on Array in JavaScript

**Hard Problems on Array in JavaScript