JavaScript Arrays

Okonu Deborah
Jul 3, 2020 · 6 min read
JavaScript
JavaScript Arrays

An array is a special variable, which can hold more than one value at a time. JavaScript arrays are lists like variables, users to store multiple values in a single variable.

A single array can store multiple data.

What makes an area special is the fact that it can hold many values.

Instead of storing data like this:

var name1 = "Debs";
var name2 = "Debbie";
var name3 = "Deborah";

We can just store multiple data like this:

var names =  ["Debs","Debbie","Deborah"]

Much efficient, right?

Creating An Array

Arrays are created with square bracket — [ ] and data are separated with commas — (,).

Using an Array Literal is the easiest way to create an array.

var array_name = [item1, item2, ...];
Arrays

Another way of creating an array is by using the Array Constructor:

var cities = new Array(“Debs”, “Debbie”, “Deborah”) ;

Note: Both the Array Literal and Array constructor would produce the same result, but for simplicity, readability and execution speed, using the Array Literal is advisable.

The new keyword only complicated the code. It can produce some unexpected results.

Accessing The Elements Of An Array

Array items are accessed using integers. You can access the element of an array by referring to the Index Number.

Note: Arrays are zero indexed. That is, it’s count starts from 0, not 1.

Example:

Indexing a
Indexing a

In the image above:

Notice that,

document.write(ary[4]); //outputs "E" and not "D"

And also,

document.write(ary[2]); //outputs "C" and not "B"

Changing An Array Element

You can change an array element, by simply assigning a new value to it.

Example:

var names = ["Debs","Debbie", "Deborah"]; //the original array elementsnames[0] = "Debby"; //assigning a new value to the first element in the array.document.write(names[0]);

This is would give a result of: “Debby” instead of “Debs” because I assigned a new value to it.

You can try it out in your text editor.

The full array can be accessed by referring to the full name:

Example:

var names = ["Debs", "Debbie","Deborah"];document.write(names);//outputs: Debs, Debbie, Deborah

Add Items To An Array

How to add items to an array

The push() method adds one or more items to the end of an array.

Example:

var names = ["Debs", "Debbie"];names.push("Deborah")document.write(names)
//outputs: Debs, Debbie, Deborah.

The unshift() method adds one or more elements to the front of an array.

var names = ["Debs", "Debbie"];names.unshift("Deborah")document.write(names)//output: Deborah, Debs, Debbie

Example:

var names = ["Debs", "Debbie"];names.unshift("Deborah")document.write(names)//outputs: Deborah, Debs, Debbie.

Remove Items From An Array

Remove items from an array

The pop() method, removes the last element of an array.

Example:

var names = ["Debs", "Debbie", "Deborah"];names.pop()document.write(names)//output: Debs, Debbie.

The shift() methods removes the first element of an array.

Example:

var names = ["Debs", "Debbie", "Deborah"];names.shift()document.write(name);//output: Debbie, Deborah.

Arrays Are Objects

Objects vs Arrays

Arrays are special types of objects with numbered indexes. The typeof operator in JavaScript returns objects for arrays.

Learn more about JavaScript operators👈.

But JavaScript arrays are best described as arrays.

One difference between JavaScript Arrays and JavaScript Object is that:

JavaScript Arrays uses numbers to access it’s elements.

Example:

var names = ["Debs", "Debbie"];document.write(name[0];//output: Debs

While

JavaScript Objects uses names to access it’s elements.

Example:

var names = {
firstName: "Debbie",
age: 20,
city: "Portharcourt"
}
doument.write(names.age)//outputs: 20

Click the link to learn more about JavaScript Objects👈.

Accessing The Length Of An Array

The length of an array represents it number of elements.

The length property of an array returns the length of an array.

Example:

var names = ["Debs", "Debbie"];document.write(names.length);//outputs: 2

To access the last element of an array, deduct one from it’s length.

Example:

var names = ["Debs, "Debbie","Deborah"];var lastItem = names[names.length - 1];document.write(lastItem);//outputs: Deborah

Looping Array Elements

Looping over an array means accessing it’s data individually.

The safest way to loop through an array is using a for loop.

Example:

var name = ["Debs, "Debbie"]for (var i =0; i < name.length; i++ {
document.getElementById("demo").innerHTML += name[i] + "<br>;
}

Note:

The + operator makes sure that the printed elements do not get over written

Associative Arrays

Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.

var person = []
person[0] = "Debbie";
person[1] = "Debs";
person[2] = 36;
var x = person.length; //person.length will return 3var y = person[0]; //person[0] will return "Debbie"

WARNING !!
If you use named indexes, JavaScript will redefine the array to a standard object.
After that, some array methods and properties will produce incorrect results.

Example:

var person = []
person["firstName"] = "Debbie";
person["lastName"] = "Debbie";
person["age"] = 36;
var x = person.length; //person.length will return 0var y = person[0]; //person[0] will return undefined

When to Use Arrays. When to use Objects.

  1. JavaScript does not support associative arrays.
  2. You should use objects when you want the element names to be strings (text).
  3. You should use arrays when you want the element names to be numbers.

How to Recognize an Array

A common question is:

How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns "object":

var fruits = ["Banana", "Orange", "Apple", "Mango"];typeof fruits; //returns object

The typeof operator returns object because a JavaScript array is an object.

Solution 1:

To solve this problem ECMAScript 5 defines a new method Array.isArray():

Array.isArray(fruits); //returns true

The problem with this solution is that ECMAScript 5 is not supported in older browsers.

Solution 2:

To solve this problem you can create your own isArray() function:

function isArray(x) {
return x.construtor,toString().indexOf("Array") > -1;
}

The function above always returns true if the argument is an array.

Or more precisely: it returns true if the object prototype contains the word "Array".

Solution 3:

The instanceof operator returns true if an object is created by a given constructor:

var fruits = ["Banana", "mango"];fruits instanceofArray; //returns true.

With this, you should be able to know how to create a JavaScript array, access them and change their elements.

In my next article, I’ll try to explain JavaScript Array methods.

Thank you for reading❤️.

Pexels.com

Remember: The way you handle your failure determines the kind of success you’ll achieve. It won’t work unless you try it📌.

Google image

Weekly Webtips

Explore the world of web technologies through a series of tutorials