What is ARRAY in Javascript — with Example

Oodo Roland Uchenna
2 min readSep 30, 2022

--

source: data-flair

An array is a special variable, which can store more than one value. It helps to group items together instead of writing them separately as shown in the example below;

// Not an Array:

let name1 = ‘Roland’;

let name2 = ‘Chika’;

let name3 = ‘Joy’;

let name4 = ‘Godwin’;

// An Array of names:

Const utiva_students = [‘Roland’, ‘Chika’, ‘Joy’, ‘Godwin’];

This is an Array named utiva_students which holds four names inside it by just writing a single line of code. That's awesome! isn't it?

NOTE: A pair of square brackets [ ] represents an Array.

//Below are the core characteristics of an Array.

Javascript Arrays are resizable — This means increasing or decreasing the size of an Array. Elements can be added or removed in an Array using the index values.

Javascript Arrays can contain a mix of different data types — With Javascript Arrays, you can create a group of items of different data types (eg. String, Boolean, Number, Objects, Arrays).

Javascript Arrays are not Associative Arrays — This simply means that Javascript Arrays cannot be accessed using arbitrary strings as indexes instead they can be accessed using a numbered index.

// Example

Const cars = [‘Venza’, ‘BMW’, ‘Ferrari’];

To access the content of the Array cars, we use a numbered index as shown below;

cars[0]; // This displays the first element of the Array car

NOTE: Associative Arrays are Arrays with named indexes (strings)

Javascript Arrays are Zero Indexed — The first element of an Array starts at index 0, the second element starts at index 1, and so on. While the last element is at the value of the Array’s length property minus 1.

Creating an Array in Javascript.

We have three simple ways to create an Array;

  1. Using Array Literal Notation
  2. Using Array ( ) Constructor
  3. Array from string.split( )

// Using Array Literal Notation — Example

To create an Array using the literal notation, we use the square brackets [ ].

Const fruits = [‘Apple’, ‘Orange’ ‘Cashew’]; //This shows an Array with three items.

//Using Array( ) Constructor — Example

Const fruits = new Array(‘Apple’, ‘Orange’, ‘Cashew’); //This also shows an Array with three items.

new Array ( ) -> This is called the Array constructor.

//Using Array string.split( ) — Example

This method is used to convert a string to an Array

Const fruits = ‘Apple, Orange, Cashew’; // This is a variable fruits, containing some strings inside

fruits.split(‘, ‘); // This converts all the elements of the variable fruits into an Array at the position of the comma (,)

console.log(fruits.split(‘, ‘)); // This will return an Array list shown below

[‘Apple’, ‘Orange’, ‘Cashew’];

Conclusion

JavaScript has many more array methods to be used. I encourage you to practice with them and learn other array methods as well. Thanks for reading!

--

--

No responses yet