Web Portal
JavaScript Array Methods
freecodecamp

freecodecamp

Apr 16, 2022

JavaScript Array Methods

A pair of square brackets [] represents an array in JavaScript. All the elements in the array are comma(,) separated.

In JavaScript, arrays can be a collection of elements of any type. This means that you can create an array with elements of type String, Boolean, Number, Objects, and even other Arrays.

Here is an example of an array with four elements: type Number, Boolean, String, and Object.

const mixedTypedArray = [100, true, 'freeCodeCamp', {}];

The position of an element in the array is known as its index. In JavaScript, the array index starts with 0, and it increases by one with each element.

So, for example, in the above array, the element 100 is at index 0, true is at index 1, 'freeCodeCamp' is at index 2, and so on.

The number of elements in the array determines its length. For example, the length of the above array is four.

Interestingly, JavaScript arrays are not of fixed length. You can change the length anytime by assigning a positive numeric value. We will learn more about that in a while.

How to Create an Array in JavaScript

You can create an array in multiple ways in JavaScript. The most straightforward way is by assigning an array value to a variable.

const salad = ['🍅', '🍄', '🥦', '🥒', '🌽', '🥕', '🥑'];

You can also use the Array constructor to create an array.

const salad = new Array('🍅', '🍄', '🥦', '🥒', '🌽', '🥕', '🥑');Please Note: new Array(2) will create an array of length two and none of the elements are defined in it. However, new Array(1,2) will create an array of length two with the elements 1 and 2 in it.

freecodecamp

freecodecamp

coding tutorials

Leave a reply

Related Posts

Categories