Javascript Arrays and Objects Tutorial

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.

Next, we can also add items to the array. We can add items in two ways:

Using index

Taking the same example of var names = ["Alex", "Billy", "Dale"];

We can add items by typing the following command:

names[3] = “Ashley”

So, the variable names now becomes:

["Alex", "Billy", "Dale", "Ashley"]

Using push() function

To use this, we give the following command:

names.push("Joshua")

So, the variable names now becomes:

["Alex", "Billy", "Dale", "Ashley", "Joshua"]

We also see that the command “names.push("Joshua")” has returned “5” as an output.

This is because the push function will return the number of elements in the array that we have by adding the new value.

Remove Element from Arrays

Now, let us see how to remove an element from the array.

We can use the splice method on our array object.

The splice method takes two parameters.

The first parameter takes the index of the array starting from which we want to remove the elements.

The second parameter takes the number of elements that we want to remove from the given starting index.  

For example, consider the array

names = ["Alex", "Billy", "Dale", "Ashley", "Joshua"];

Now we want to get rid of Billy and Dale.

So we give the following command:

names.splice(1, 2)

(Here we need to choose the index that we want to start up which is 1 for Billy)

It gives the output:

["Billy", "Dale"]

So, the variable names now becomes:

["Alex", "Ashley", "Joshua"];

So that is how we create arrays in Javascript and modify them. We’ve been doing this all in the console. We could do this exactly the same within our code.

Let’s just take a look at the code given below:

This program summarizes what we have learned about arrays.

The next topic to learn is working with objects and that’s having an associative array. which means that we have the indexes as named values. So, we want to change this array and want to create an element at the end of this.

Taking the array -

var names = ["Alex", "Billy", "Joshua", “Ashey”, “Sheeba”];

Consider the command:

names[‘colour’] = ‘Blue’;  

Usually, we would find or access array elements using their index. But here, in the code above, we’ve added a named index. So this has now become partly an associative array.

The above command, when executed, gives the value of the array as follows:

["Alex", "Billy", "Joshua", “Ashey”, “Sheeba”, colour: “Blue”]

We see that instead of just another element, we"ve got color blue.

Well, we know that the variable names contains all these values, but what happens if we actually want to go ahead and access this?

We can do this by giving the command:

names.colour

The output is - “Blue”

We can do the same with the objects.

The above sections provided a good understanding of how we create, append, modify, splice the arrays in javascript. We also learned how to add named indexes to arrays.

Array Prototype

Here, we look at some of the properties and methods that are available in arrays that we may create.

Consider the same array variable ‘names’ with values as shown:

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

Array objects or instance actually inherit from array.prototype. Array.prototype contains different properties and basically allows you to perform different actions on arrays. We've already looked at things like splice, which is actually inherited from array.prototype.

For example, let's take a look at the length property of the array ‘names’.

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

console.log(names.length);

At the console, we get the output: 3

Now at the console, type the following:

Object.getOwnPropertyNames(names)

Now what this will return is all of the property names of this particular object (remember it's an array, but it is classed as an object). So we've get the output:

[“0”, “1”, “2”, “length”]

Here, the property names are 0, 1, 2 which are the indexes and the fourth property name is length, which contains the length of the array.

Some of the other methods that are a part of array.prototype are discussed below:

pop( )

It removes the last element from the end of an array and it will return that element.

push( )

It returns the new length of the array after adding one or more elements to it.

reverse( )

Reverses the order of the elements in an array.

sort( )

Sorts the elements of the array and returns it.

Along with the above methods, we also have other categories like accessor methods, iteration methods etc.

Looping over Array

Let us take a look at how we can iterate over arrays to access each of the element properties in a list.

Here, we will discuss the ‘for’ loop and ‘forin’ loop. Now the difference between forin and a for is that forin is going to specifically iterate over the new properties of an object. However, it will not necessarily return them in index order.

Consider the array shown below:

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

For example, let's say we want to loop over ‘names’ and just output the elements to the console. This can be done by the following code:

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

for(name in names) {

console.log(names[name]);

}

The above code gives the output:

Alex

Billy

Dale

Here, the ‘name’ variable starts from zero and and remains valid till the number of elements in the array. It increments each time the for loop executes and prints the elements as shown above. The problem here is that with this loop, we may not the get the output strictly in index order.

So, if you wish the output to be in a particular order, we can use the for loop as shown.

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

for(var x = 0; x<= 2; x = x + 1) {

console.log((names[name]);

}

The output for the above code will be:

Alex

Billy

Dale

Here, we have used a for loop which requires a variable ‘x’ with initial value that can point to index 0 of the array. Then we provide a condition for the number of times that we wish to use the loop. Next, we increment the variable for the loop to continue till the end.

Here, we are sure that the output will be displayed in the desired order.

Now, the order here is fixed. In the above example, the loop will always run for only three times.

But what if we have more than three elements in the array?

To solve the problem, we need to have a dynamic condition so that the loop runs for all the elements it contains. It can be done as shown:

var names = ["Alex", "Billy", "Dale", “Ashley”];

for(var x = 0; x<= names.length - 1; x = x + 1) {

console.log((names[name]);

}

Here, we have given a dynamic condition which works for the entire elements of the array. Notice that we have used ‘names.length - 1’. It is because the length property counts from 1,2, and so on. But the index of arrays starts from 0. Hence the condition becomes so.

Now we are going to look at objects in javascript and exactly what objects are. Well then let us take a look at how we actually define an object.

The first thing to know is that in javascript, most things are objects. We've already looked at variable types like strings, integers, etc.

What happens if we create a string? We want to find out the length of that string, for example. We want to go ahead and search for a particular character within that string.

Well, we have methods that are available on the actual string that we create, so what we'll do is create a variable within the app.js file and we'll start to have a look at this variable that we create.

Now bear in mind this is a string, but we're actually looking an introduction to object so well, find now that this string actually is an object and has its own methods that we can use.

Let us create this name variable that will just be a simple string

var name = ‘Alex’;

When we just write ‘name’ at the console, we get the result “Alex” back as a string.

Now, what happens if we want to access the length of this string?

In other programming languages, you might be used to doing things like using strlen( ) and then entering the name of the variable you want to find the string length of.

In javascript, we have a list of methods already attached to the object prototype and the string inherits from the object prototype.

So, instead of using the strlen function, we just type

name.length

And we get the result: 4

This length property holds the amount of the characters in this string and will return to us that value.

Note: As we go on to type ‘name.’ (variable name followed by a dot) a drop-down menu appears with the list of all the properties that can be performed on the string variable.

Remember that properties are variables, and methods are functions. They are methods and properties only when they become part of the objects.

So if they were stand-alone, they would be variables and functions.

Now, there is a property called charAt( ) which is a method and it allows you to pick a character from your string based on its position.

Remember that strings are zero indexed. So if we type

name.charAt(0)

We get the result: “A”

Then, we have the search method and is used as follows.

name.search(‘A’);

We get the result - 0

Then if we write the command

name.search(‘y’);

We get the result: -1

So the search method returns the position of the character that we try to find. If the character is not present in the variable value, it will return ‘-1’ which is a common concept in programming languages.

So you can see here that even though we're working with a string were actually working with an object.

Now, let's do the same thing but this time using actual string and you'll see that this still works.

Give the command at the console as:

“Alex”.length

We get the output: 4

We can use the same function with array objects as well. The code is as shown:

[‘Alex’, ‘Dale’, ‘Billy’].length

We get the output: 3

Now, let us learn the object literals. It's creating your own object rather than using objects that have already been created for you. So when we created the string name, it was the object that was already created for us and we had all the properties associated with it.

Let us create our own object.

var app = { };

Now if we write ‘app’ at the console, it gives the output:

Object { }

Now let’s say

app.name = “Javascript”;

Now if we write ‘app’ at the console, it gives the output:

Object {name: “Javascript”}

We can also give the command:

app.name.length

It gives the output: 10

So this is how we create objects basically.

Creating an Object

Let us define our first object, apply a property to this object, and then define a method.

Consider the code shown below;

var app = { };

app.version = 1.0;

Here, we have defined an object and assigned the ‘version’ property to this app object and stored the value 10 within it.

So now when we type ‘app’ at the console, we get the output:

Object {version: 1}

Consider the code shown below:

var app = {

version: 1.0,

Name: ‘Brilliant app’

};

Now, if we try to type ‘app’  at the console, it will give the output

Object {version: 1, Name: ‘Brilliant app’}

Let us see how do we actually make use of creating functionality all within this object. Because it's best practice to create all of your functionality within this app as well.

There are a few ways to define functions in javascript. Consider the code shown below:

var app = {

version: 1.0,

Name: ‘Brilliant app’

};

function getVersion( )

{

return app.version;

}

The above function will work fine because it is defined globally.

When we call the function at the console, by typing: getVersion( )

We get the output: 1

Now the problem here is that we've created a global function which we don't want to do. We want to create everything within our app object.

Let us get rid of that global function. Consider the code below:

var app = {

version: 1.0,

Name: ‘Brilliant app’,

getVersion: function( ) {

return app.version;

}

};

Now, if we try to type ‘app’  at the console, it will give the output

Object {version: 1, Name: ‘Brilliant app’, getVersion: function}

Now, if we call the function:

app.getVersion( )

We get the output: 1

We can also use ‘this’ keyword to refer to the ‘app’ object since ‘this’ refers to the object as a whole. The code just requires a small change as shown

var app = {

version: 1.0,

Name: ‘Brilliant app’,

getVersion: function( ) {

return this.version;

}

};

The output still remains the same even if we use the above code.

So that's basically how we create a very simple object. We've also talked a little bit about how we should namespace things under a single object just to make things a little bit easier for ourselves. This is done so that we don't get any name in conflicts.

Javascript Dates and Time

We're now going to have a look at working with dates and times in Javascript. Here we'll take a look at the date object, which contains various methods that allow you to get back all sorts of information or properties about the current time.

And this is based on the local time of the system the person is using. So you can't rely on this for things like actual times, because a user can change the time on their system. So bear in mind that these are always local times.

Let us introduce the date object. We're going to use the new keyword, which we haven't seen yet, and this will create a new instance of the date objects. Consider the statement below:

var date = new Date( );

Here, we have created a new instance of the date object which instantiates it and allows us to access its properties and method.

When we type ‘date’ at the console now, it will automatically return out the human-friendly version of the date.

It gives us the date, the time, the time zone, and then gives us a textual representation of the times. It displays the time that exactly matches with the local machine.

Let us look at some of the methods or properties that you can use here.

At the console, we need to type ‘date.’ (date followed by the dot) which then shows a list of properties can be used with this variable.

For example, to get the time, we type

date.getTime( )

The above statement will return a timestamp of the current time.

To get the current year, we would write

date.getFullYear( )

The result displays the current year.

Javascript Intervals

Now let us study the setinterval function in javascript. It essentially allows you to actually set a timer(by coupling with clear interval) that goes every x amount of milliseconds that you provide. In this section, we’ll have a look at the syntax; create just a global variable; create a loop for every second, and then output something every second at the console.

It is extremely useful for a variety of different things.

For example, it can be used in animation. We can animate the elements on our page using this set interval.

We can scroll to the top of a page, to animate a whole page, scroll effect up things and so on.

Let us look at the syntax for creating an interval and how we actually pass in the required functionality. There were two different ways that we can do this.

Consider the code shown below:

var getTime = function( ) {

console.log(new Date( ).getTime( ));

},

interval = setInterval(getTime, 1000);

The function getTime( ) will return the current timestamp, each time we call it at the console.

For the interval function, two parameters that we need are the name of the function that we want to run every amount of milliseconds, and the amount of milliseconds.

Here we have passed 1000 which means 1 second.

When we refresh the console, it outputs a new time stamp every second(without stopping).

Now we need to clear this interval because it will just carry on as long as the browsers open and as always, the coats running.

Now, let’s say we wish to count from one to ten and then stop it ten and clear the interval.

Consider the code shown below:

var x = 1,

interval = setInterval(function( ) {

console.log(x);

x++;

}, 1000};

At the console, it would start printing 1,2,3, and so on. It will carry on counting until we refresh the page or close the browser.

Now, we need to create an if statement to stop it at 10. The following code does that.

var x = 1,

interval = setInterval(function( ) {

console.log(x);

if(x === 10) {

clearInterval(interval);

}

x++;

}, 1000};

One thing that you need to bear in mind with an interval, is that the appearance of the initial output at the console depends upon the time that we provide in the interval.

For example, consider the code shown below:

var interval = setInterval(function( ) {

console.log(‘Hello’);

}, 5000};

When we refresh the console, we find that the initial output Hello takes five seconds to appear on the screen since the time provided is 5000 milliseconds.

Countdown (Example Application)

Now, we are going to focus on building an example application. This example application is basically going to count down from a specific number to another number.

Here, we're going to look at passing an object as a property to a function; then we are going to check if the settings are defined with a series of if statements, and so on.

The countdown that we explain here is as shown:

app.countdown({startAt: 5, endAt: 1})

Its output will be:

5

4

3

2

1

So let’s understand how to create a countdown.

The first thing to do is really just define our app object that we're going to be using remember

var app = { };

app.countdown = function(settings) {

console.log(settings);

};

The app variable here is going to store our method for our countdown. We create a function and assign it to a countdown method within our app.

When we try to see the output at the console on calling the countdown function, it gives the output: ‘undefined’

Next, if we give the command

app.countdown({ })

It gives the output:

Object { }

undefined

We still get undefined because if we don't return something explicitly, it will always return undefined automatically.

Let’s move ahead and declare variables inside the countdown.

var app = { };

app.countdown = function(settings) {

var interval,

counter =0;

// start and end points

startAt = 0,

endAt = 0;

if(settings === undefined)  {

console.log(‘Please provide settings’)

}

else {

console.log(‘Ok’);

}

};

At the console, if we give the command with no settings like:

app.countdown

It gives the output:

Please provide settings

undefined

If now we provide setting as an object:

app.countdown({ })

It gives the output:

Ok

undefined

Next, let us create the countdown with the following code:

var app = { };

app.countdown = function(settings) {

var interval,

counter =0;

// start and end points

startAt = 0,

endAt = 0;

if(settings === undefined)  {

console.log(‘Please provide settings’)

}

else {

If(settings.startAt === undefined || settings.endAt === undefined) {

console.log(‘Start and end numbers are required’);

{

else {

startAt = parseInt(settings.startAt, 10);

endAt = parseInt(settings.endAt, 10);

if(!isNaN(startAt)  && !isNaN(endAt)) {

counter = startAt;

Interval = setinterval(function() {

if(counter < endAt) {

console.log(‘Finished’);

clearInterval(interval);

}

else {

console.log(counter);

}

counter =counter - 1;

}, 1000);

}

}

};

For the above code, let’s check the output at the console by giving the command

app.countdown(startAt: 5, endAt: 1})

So we get the output

undefined

5

4

3

2

1

finished

So we have a fully working countdown application.

Callbacks

In this section, we're going to look at callbacks in javascript, what they're used for and how to implement them.

But in actual fact they're extremely powerful to implement. Let us understand it with the help of an example shown below:

<script>

app.add([5, 6], function(result) {

console.log(‘The result is’ + result);

});

</script>

As can be seen, there is an add method defined in the app.js file which adds numbers.

Here, for the function add, there are two parameters: one is the array and the other is the callback function. So the callback function is used to fetch the result of the added numbers and then displays it.

Instead of just displaying the result, we can perform more operations on it, using this callback function. Hence, this function has the control over the result, independent of the add function in app.js.

So, let’s understand how can we do this from the scratch.

We first need to write the code for the add function.

var app = { };

app.add = function(numbers, callback) {

var result = 0;

if(numbers !== undefined  && numbers.length) {

for (number in numbers) {

result = result + numbers[number];

}

if(callback !== undefined) {

callback(result);

}

}

}

The above code can be checked in the script as follows:

<script>

app.add([5, 10], function(result) {

console.log(‘The result is’ + result);

});

</script>

The output at the console is:

The result is 15

And even if we modify our array as shown:

<script>

app.add([5, 10, 4], function(result) {

console.log(‘The result is’ + result);

});

</script>

The output will be:

The result is 19

So, irrespective of how many inputs we have for add function, we can fetch the result and use it through callback function.

Callback in Countdown Application

In this section, we're going to modify the countdown application that we created in previous sections. We're going to modify the countdown application to actually allow for a callback.

We wish to enhance the flexibility of this application to pass a call back when we call the countdown method. This will just allow us to output wherever we want or do whatever we want when the countdown reaches zero.

Let's take a look at the initial code for countdown application.

var app = { };

app.countdown = function(settings) {

var interval,

counter =0;

// start and end points

startAt = 0,

endAt = 0;

if(settings === undefined)  {

console.log(‘Please provide settings’)

}

else {

If(settings.startAt === undefined || settings.endAt === undefined) {

console.log(‘Start and end numbers are required’);

{

else {

startAt = parseInt(settings.startAt, 10);

endAt = parseInt(settings.endAt, 10);

if(!isNaN(startAt)  && !isNaN(endAt)) {

counter = startAt;

Interval = setinterval(function() {

if(counter < endAt) {

console.log(‘Finished’);

clearInterval(interval);

}

else {

console.log(counter);

}

counter =counter - 1;

 

}, 1000);

}

}

};

So now to include the callback function, we modify the code as shown below:

var app = { };

app.countdown = function(settings, callback) {

var interval,

counter =0;

// start and end points

startAt = 0,

endAt = 0;

if(settings === undefined)  {

console.log(‘Please provide settings’)

}

else {

If(settings.startAt === undefined || settings.endAt === undefined) {

console.log(‘Start and end numbers are required’);

{

else {

startAt = parseInt(settings.startAt, 10);

endAt = parseInt(settings.endAt, 10);

if(!isNaN(startAt)  && !isNaN(endAt)) {

counter = startAt;

Interval = setinterval(function() {

if(counter < endAt) {

if(callback !== undefined) {

callback( );

}

clearInterval(interval);

}

else {

console.log(counter);

}

counter =counter - 1;

}, 1000);

}

}

};

Now let's call the countdown application in the script.

<script>

app.countdown({startAt: 3, endAt: 1}, function( ) {

console.log(‘The countdown has finished’);

});

</script>

So, the output will be:

3

2

1

The countdown has finished.

So this is how we modify our countdown application to work with a callback function.

Summary

  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*