Javascript Array

Javascript Array

·

3 min read

What is Javascript Array?

An array is a very powerful data structure in Javascript. Arrays are like an object that can store a collection of items in a single variable.

Few important points related to Javascript Arrays -

  • Array becomes really helpful when you need to have a list-like object and you wanted to perform the same operation on each of them.

  • You can access any items in an array by referring to its index and the index of the first element of an array is zero (Always an Integer!).

  • Length of a JavaScript array and the types of its elements are not fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array. Yes, it means you can have an array like - [1, 2, empty, 4]. 😎

Creating an Array

The go-to way

Idea ➡️ We will create our array with values movies, books, and painting. Index for each item will be 0, 1, and 2 respectively. And we will access the items using their indices -

Implementation ⬇️

let hobbies = ['movies', 'books', 'painting'];
let x = hobbies[0];   // x = movies
let y = hobbies[1];   // y = books
let z = hobbies[2];   // z = painting

The Array Constructor way

We can also create an array using an Array constructor like this

let hobbies = new Array('movies', 'books', 'painting');

The start with an empty array way

let hobbies = new Array();
// OR
let hobbies = [];
hobbies[0] = 'movies';
hobbies[1] = 'books';
hobbies[2] = 'painting';

Changing an Array Element

We can also change an item of an array

hobbies[1] = 'photography';

This will overwrite the value at index 1 from books to photography.

hobbies = ['movies', 'photography', 'painting'];

The length Property

This property will tell us about the size of the array. It returns the total number of array elements.

let arraySize = hobbies.length;  // arraySize = 3

The length property is always one more than the highest array index.

How to check if a variable is an Array

The problem here is typeof hobbies will return object. So, what now? Well, you can check in the following way

isArray() method

Array.isArray(hobbies);

But above won't work in an older browser as ECMAScript 5 is not supported there.

instanceof operator

hobbies instanceof Array;

Array OR Objects

When to Use Arrays and when to use Objects -

  • JavaScript does not support associative arrays.
  • Use objects when you want the element names to be strings.
  • Use arrays when you want the element names to be numbers.

That's all for this post. I will write about Array methods in my next post

Thanks for reading. 🖤