JavaScript - Array




JavaScript - Array

An array is an object used to store a collection. This collection could be anything: numbers, objects, more arrays, etc. In JavaScript, arrays are used to store multiple values in one variable that can be accessed through an index (which starts from zero). The values stored in the array are called elements and the number of elements stored in an array is typically referred to as the array’s length. For example, in the illustration given below, the length of the array is five:

We have learned that a variable can hold only one value, for example var i = 1, we can assign only one literal value to i. We cannot assign multiple literal values to a variable i. To overcome this problem, JavaScript provides an array. An array is a special type of variable, which can store multiple values using special syntax. Every value is associated with numeric index starting with 0. The following figure illustrates how an array stores values.

We now move on to look at Arrays in Javascript, which is slightly more complicated than what we’ve already looked at. We’re still dealing with variables, so this could be considered a type of variable. An array in Javascript could just be assigned to a variable, as you would with the var keyword.

Objectives

By the end of this lesson on Javascript Arrays and Objects, you"ll be able to -

  • Create arrays.

  • Use the array object, array notation.

Essentially, an array is a data type in Javascript that actually stores a list of particular items within it. Let’s just take a look at creating an empty array or creating an array with a few values in maybe console logging it, and what it looks like when we output it to a page. How we can access each item of the array and how we can append things to arrays as well.

Create Arrays

So the first thing that we’re going to do is create a variable called “names” and that’s going to be this empty array as shown -

var names = [ ];

In the console, when we type "names", we can see that we just have an empty array as shown -

[ ]

When we give the command "typeof names", we get -

object

Now, it’s a little bit strange because we’re talking about arrays and not objects.

So why is an array an object?

Well, it’s stored as an object but it is still treated as an array.

So, now we can start to build up the list of things that we actually want to include in our array.

For example,

var names = ["Alex", "Billy", "Dale"];

The above values are all string values and they are comma-separated. At the console, we get three string items within this array, when we give the command "names". Let’s see what happens if we want to also include few numbers in this array.

For example,

var names = ["Alex", "Billy", "Dale", 24, 80, 45];

When we go to the console, we see that the above declaration is perfectly valid. We can include a mixture of different data types within an array. We can even include objects within it, as shown below -

var names = ["Alex", "Billy", "Dale", 24, 80, 45, { }];

Let’s first take a look at accessing elements of an array. Let us consider an array with three names as shown -

var names = ["Alex", "Billy", "Dale"];

We want to get the first element of this array. We need to type the name of the variable and square brackets with an integer in it.

names[ ]

The integer represents the index that each of the items is assigned. Arrays in javascript are zero indexed, which means that the first element has the value of zero, the second has the value of one, and so on.

So when we write: names[0]

The output shows -

Alex

Similarly for names[1]

The output shows -

Billy

So this is how we access elements.

We can also set values as shown below -

names[0] =  “Joshua”

Next, when we give the command "names", it gives the output -

["Joshua", "Billy", "Dale"]

Here, the previous value at zero index has been overwritten by referencing it through its index number zero.

JavaScript Array

Javascript objects are really nice, but sometimes they are missing some useful little functions/methods. The example above is with Arrays. It’s really nice to know whether or not an item is contained within your array. Well you can write a function that takes the array and the item you’re checking for, but it’s much cleaner to add the contains( item ) method to the Array object.

/**
 * Array.prototype.[method name] allows you to define/overwrite an objects method
 * needle is the item you are searching for
 * this is a special variable that refers to "this" instance of an Array.
 * returns true if needle is in the array, and false otherwise
 */
Array.prototype.contains = function ( needle ) {
   for (i in this) {
       if (this[i] == needle) return true;
   }
   return false;
}

Usage

// Now you can do things like:
var x = Array();
if (x.contains('foo')) {
   // do something special
}

How to add an item to an array

We can add an element at the end of an array using the push() method -

a.push(4)

We can add an element at the beginning of an array using the unshift() method -

a.unshift(0)
a.unshift(-2, -1)

How to remove an item from an array

We can remove an item from the end of an array using the pop() method -

a.pop()

We can remove an item from the beginning of an array using the shift() method -

a.shift()

How to join two or more arrays

You can join multiple arrays by using concat() -

const a = [1, 2]
const b = [3, 4]
const c = a.concat(b) //[1,2,3,4]
a //[1,2]
b //[3,4]

You can also use the spread operator (...) in this way -

const a = [1, 2]
const b = [3, 4]
const c = [...a, ...b]
c //[1,2,3,4]

Arrays are a a powerful and comprehensive tool of Javascript. They are very intuitive to use and you can do almost everything with it. However, there are important differences between arrays in Javascript and other mainstream languages. Knowing them will help you unleash their true potential. In this article we will go through the important aspects of arrays that are imperative to every JS developer and we will see the variety of usages they have.

Arrays are just regular objects

In Javascript, there are only 6 data types defined – the primitives (boolean, number, string, null, undefined) and object (the only reference type). Arrays do not belong to this list because they are objects as well. This is a common confusion among developers who assume that arrays are a special data type in Javascript. The items in the array are nothing more than properties of that objects. You can use any name as property for an objects, including numbers or even empty string. However, if the property name is not a valid identifier (doesn’t start with a letter), you can only access it through obj[property_name] and not obj.property_name. So nothing stop us from taking an object and declaring properties like 0, 1, 2 and so on and accessing through obj[0], obj[1] and so on. You don’t need a special data type for doing that in Javascript.

// just your average object 
var obj = {
0: 1,
1: 2,
'cat': 'meaow', 
'': 'empty string'
};

console.log(obj[0], obj[1], obj['cat'], obj['']);
1 2 meaow empty string

So you may ask: What is special about array object then? An array has, alongside its elements, a special property named length and a generous collection of methods for manipulating the elements. They represent the real power of arrays. You can search, sort, delete, insert and even simulate behavior of other collection data types, like queue and stack.

Declaring an array

Javascript’s elegance owes a lot to its concise literal syntax for the most common building blocks: object, functions and array. A literal is the best way to express an array -

var arr = [1, 2, 3, 4];

There is an alternative to that, the Array constructor -

var arr = new Array(1, 2, 3, 4);

Setting aside the aesthetics, there some subtle things you have to care about when using the array constructor. Since Array is a global variable, it can be modified somewhere else in the script so it may not behave as you expected.

Array = String; 
var arr = new Array(1, 2, 3, 4); // "1" 

One other issue is that if the Array constructor gets only one numerical argument, it will create a list with no elements but with length equal to that argument. So ['John'] is identical to new Array('John') but [10] it’s not the same thing to new Array(10). It is possible to omit the new operator when using the Array constructor. It has the same result so new Array('John') or simply Array('John') are doing the same thing.

Array methods

It’s time to finally see them in action, Any array object has access to a set of methods trough Array.prototype. Since we are talking about a global object, these methods can be altered. It is strongly advised against doing that. Modifying the Array.prototype will affect all the arrays in that global context. However, I often encounter situations where the prototype scope was augmented by adding other helper functions to Array.prototype. For example, by default there is no method to return the first element of the array (without deleting it). You can add your own custom method −

var arr = [2, 2, 3, 4]

Array.prototype.first = function() {
return this[0];
}

console.log(arr.first()); // prints 1

And now every array in our global scope has access to the first() method. This may be convenient in some situations, but is generally a bad idea. If you modify a prototype, there is always the possibility to clash with other code from your program. I compile below a list of methods that I consider important and worth to be remembered. It is a good practice to walk through all of them and practice in parallel. Of course, nobody knows by heard all the details about them, but once you understand the behavior, you know where to search when you need it.