Arrays in JavaScript

CodingTute

JavaScript

An array is a special kind of data structure that is used to store a collection of values. Each value in an array is called an element, and the elements are separated by commas.

You can create an array using the Array constructor or the array literal syntax, which is a pair of square brackets ([]) enclosing a comma-separated list of values. For example:

const arr1 = new Array(1, 2, 3);
const arr2 = [1, 2, 3];

Both arr1 and arr2 are equivalent arrays that contain the elements 1, 2, and 3.

You can access the elements of an array using their indices, which are integer values that indicate the position of the element in the array. The first element has an index of 0, the second element has an index of 1, and so on.

You can use the square brackets notation to get or set the value of an element in an array. For example:

const arr = [1, 2, 3];

console.log(arr[0]);  // Output: 1
console.log(arr[1]);  // Output: 2
console.log(arr[2]);  // Output: 3

arr[0] = 10;
console.log(arr[0]);  // Output: 10

An array can store elements of any data type, including numbers, strings, booleans, objects, and even other arrays. This means that you can have an array that contains a mix of different types of elements.

For example:

const arr = [1, 'hello', true, { key: 'value' }, [1, 2, 3]];

This array contains the following elements:

  • A number (1)
  • A string ('hello')
  • A boolean (true)
  • An object ({ key: 'value' })
  • An array ([1, 2, 3])

Note that JavaScript arrays are not strongly typed, which means that you don’t have to specify the type of data that an array will store when you create it. This allows you to store elements of different types in the same array.

JavaScript arrays are dynamic, which means that you can add or remove elements from an array at any time. You can use the push() method to add an element to the end of an array, or the unshift() method to add an element to the beginning of an array. You can use the pop() method to remove the last element of an array, or the shift() method to remove the first element of an array.

For example:

const arr = [1, 2, 3];

arr.push(4);  // arr is now [1, 2, 3, 4]
arr.unshift(0);  // arr is now [0, 1, 2, 3, 4]
arr.pop();  // arr is now [0, 1, 2, 3]
arr.shift();  // arr is now [1, 2, 3]

There are a lot of built in array methods, which we can discuss about in further JavaScript tutorials.

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.