Object data types

Let's now go over some of the most common object types in JavaScript.

1. Arrays

The first data type to explore is arrays.

An array is an ordered collection of data.

An array is like a sequence of values or a list of items. It has the capability of storing multiple values under one hood. The individual values of an array are formally called elements, or items, of the array.

Each element sits at a given position, formally known as its index in the array. The total number of element is referred to as the array's length.

Strings and arrays are both sequences of data. Hence the same concepts of indexes and length apply to both of them.

Array elements can be of any data type. They could be numbers, strings, Booleans — simply anything. They could even be arrays. We'll explore such cases in detail in the JavaScript Arrays — Basics chapter.

Moreover, it's not required for the elements of an array to be of the same data type. An array could, for example, contain numbers and strings.

Let's now see how to create an array.

An array could be denoted 'literally' using a pair of square brackets ([]). Each element of the array goes within the brackets, and is separated from another element using a comma (,). Such an array, denoted directly using [], is called an array literal.

There is another way of creating an array and that is using the Array() constructor. We'll see it in action in the JavaScript Arrays unit.

In the following code, we create an array literally and store it in a variable nums:

var nums = [1, 5, 10];

This array is comprised of three elements: 1, 5 and 10.

Accessing a given element from an array has the same syntax of accessing a character from a string.

That is, we start by writing the array value, followed by a pair of square brackets ([]), and then put the index of the element, that we wish to access, inside these brackets.

Below we access the first and last numbers in the nums array created above:

nums[0]

1

nums[2]

10

Accessing an out-of-range index yields undefined:

nums[3]

undefined

nums[-1]

undefined

As with strings, we could obtain the total number of elements in an array using its length property.

Let's see what gets returned by inspecting the length of our nums array:

nums.length

3

As expected, we get 3, which rightly aligns with the total number of items in the array.

Storing and merely retrieving values from an array isn't interesting, and usually not what happens in applications where arrays are used. When arrays are used, they are often processed.

One common operation performed on arrays is sorting.

This is accomplished using the array method sort().

By default, sort() sorts the elements of an array alphabetically. In particular (by default) it converts each element into a string, and then performs the comparisons between the resulting string values to determine which one should come first, which one should come second, and so on.

Note that sort() sorts a given array in-place. This means that the actual array is modified in the sorting operation; not a new one created.

Consider the following code:

var langs = ['Python', 'JavaScript', 'C++', 'C', 'Java'];

langs.sort();

console.log(langs);

First, we define a variable langs and initialize it with an array. Next, we call the sort() method on this langs array. This sorts the items in it in alphabetical order. Finally, we log the array.

["C", "C++", "Java", "JavaScript", "Python"]

See how each subsequent value in this sorted list is alphabetically larger than the previous value.

Owing to the fact that sort(), by default, converts each value in the respective array into a string before the sorting routine, we couldn't sort numbers correctly using this method, as is.

Consider the following snippet. See how the numbers are arranged in the sorted list:

var nums = [100, 9, 80, 2, 0, -1, -50]

undefinednums.sort()[-1, -50, 0, 100, 2, 80, 9]

-1 appears before -50 even though it is greater than -50. Similarly, 100 appears before 2, while 80 appears before 9 and after 100. It's just a total mess!

To sort numbers correctly using sort(), we have to pass it an argument that specifies the way in which to sort the elements. This argument needs to be a function.

Consider the following snippet:

[100, 9, 80, 2, 0, -1, -50].sort(function(a, b) { return a - b; })

[-50, -1, 0, 2, 9, 80, 100]

This time, the sorted array has the given elements arranged correctly, thanks to the function provided as an argument to sort(). That how exactly does this argument function work, and why exactly do we need it will be explored, in detail, in the chapter JavaScript Arrays — Sorting.

For now, we could, however, better understand what a function is and how it works.

2. Functions

No programmer can negate the importance of functions in programming — they play an integral role. Some programming languages are largely built upon the idea of functions. Some consider functions on the same lines as other values.

At the core, the idea of a function is elementary, yet extremely powerful.

Let's see what a function is.

A function defines a piece of code that gets executed when the function is called.

A function is used to group together some code that could be executed later on at will. This execution is initiated by calling — or better to say, invoking — the function.

In JavaScript, functions could be named or anonymous. For now, we are concerned with the former, i.e. named functions.

The function keyword is used to create a function in JavaScript.

Shown below is the syntax of creating a named function:

function functionName(parameterList) {
   statements
}

We start with the function keyword, followed by the name functionName of the function (recall that functionName is a placeholder that you ought to fill with actual text). This name has to abide by the variable naming rules of JavaScript that we saw in JavaScript Variables — Rules for naming variables.

After this, comes a pair of parentheses (()) and within them the parameters of the function. We'll see what are parameters later on in this section.

Finally comes a pair of curly braces ({}) denoting the function's body. The body consists of statements that are executed when the function is invoked.

As a whole, the code above defining a function is referred to as the function's definition.

To call a function, we simply write its name followed by a pair of parentheses (()). This pair of parentheses serves to call, and likewise execute, the function. Without the parentheses, we'd be simply referring to the function's definition.

Alright, with a lot of theory been discussed, it's finally time for some examples.

In the code below, we create a function named sayHello to greet the user:

function sayHello() {
   var name = prompt('Enter your name:');
   document.write('Hello, ' + name + '.');
}

Inside the function, first we ask for the user's name via prompt() (which is yet another function!) and then output the greeting message via document.write() with the input name included.

Let's now call this function:

function sayHello() {
   var name = prompt('Enter your name:');
   document.write('Hello, ' + name + '.');
}

sayHello();

The last statement here calls sayHello by virtue of the parentheses following it, i.e. sayHello(). This, in effect, executes the code defined inside sayHello.

Quite simple, wasn't it?

Moving on, a function can take additional data to perform its task. For instance, a function made to add two numbers together might accept those numbers as additional data when we call the function.

Such additional pieces of data are called arguments, or sometimes as args. Arguments to a function go inside the pair of parentheses (()) when calling the function.

The name with which we refer to each argument inside the function is called a parameter. Parameters go inside the pair of parentheses (()) when defining a function.

By that means,

A parameter is the name with which we refer to a value passed to a function while an argument is that actual value.

You'll see the terms 'arguments' and 'parameters' used interchangeably out there. Although, this is not completely wrong, it's still good to know of the distinction between both these ideas.

Let's consider another example.

Following we define a function sum() to compute the sum of two numbers:

function sum(a, b) {
   console.log(a + b);
}

As can be seen, the function has two parameters a and b that get added and the result, ultimately, logged to the console.

Let's now call this function, with a couple of arguments:

function sum(a, b) {
   console.log(a + b);
}

sum(10, 20);
sum(10, -5);
sum(10, 30.5);
sum(0, 0);

30 5 40.5 0

Simple! Wasn't it?

Usually when setting up functions, it's desired to get a function to return back the result of the computation instead of displaying it on some medium such as the HTML document.

In this way, we could reuse the function in numerous contexts. For instance, we could pass it to document.write() or console.log() to display the result in the respective location, or assign it to a variable, or even pass it on to some other function as an argument.

The possibilities are endless!

This return keyword is used to return a value from a function.

The return keyword returns a value from a function when it is called.

The expression to be returned is mentioned right after the return keyword, which itself comes inside the function's body.

Here's the syntax for return:

function functionName(parameterList) {
   statements
   return expression;
}

Let's consider an example.

We'll redefine the sum() function that we created above to simply return the sum of a and b, instead of logging it:

function sum(a, b) {
   return a + b;
}

Let's now make a couple of calls of this function from within the console.

sum(10, 20)

30

sum(10, 20) + 50

80

sum(10, -11) * 10

-10

console.log(sum(10, 20))

30undefined

sum(10, 10) * sum(5, 5)

200

As is apparent here, the return value of sum() merely replaces the function's invocation expression and is being used just like a normal number.

There is a lot more to the beautiful and powerful world of functions in JavaScript. We'll learn more about them in the JavaScript Functions unit.

3. Objects

A large part of our time coding in JavaScript will be devoted to working with objects.

Objects are the cornerstone of JavaScript. JavaScript, as we shall explore in more detail in the JavaScript Objects unit, is an OOP (Object-Oriented Programming) language by design. This simply means that it's built around the idea of objects.

But what is an object?

An object is a set of properties and methods.

Properties define the characteristics of an object while methods define its behavior, its actions.

Objects in JavaScript, and other programming languages, work pretty much the same way as objects in the real world. Let's understand this with the help of a real-world object.

Think of real-world objects

Take, for example, a toaster oven. It's an object used in everyday life, used for simple baking concerns like baking a scrumptious pound cake or maybe even some delicious cookies.

What characteristics can you think of a toaster oven?

Well, it could have a model number, a warranty period, a body color, a temperature grading, a size, an electrical power rating, and so on. These are the properties of the oven.

Similarly, what behavior, or actions, can you think of a toaster oven?

Well, we could switch the oven on or off, heat the top or the bottom element, turn on the fan, set up a timer, and so on. These are the methods of the oven.

There are many different kinds of objects in JavaScript. Arrays, as we saw above, are objects. Functions are objects too.

In this section, we are concerned with the actual object data type in JavaScript that denotes the purest of all objects.

Here's the syntax of an object literal:

{key1: value1, key2: value2, ..., keyN: valueN}

We start by writing a pair of curly braces ({}). Inside these braces, we put individual key-value pairs for the object, separated using commas (,). Within each name-value pair, the property name comes first and is separated from the value using a colon character (:).

More readably, this syntax code could be represented as follows:

{
   key1: value1,
   key2: value2,
   ...,
   keyN: valueN
}

Let's consider an example.

We'll create an object with two properties x and y holding the values 10 and 20, respectively:

var obj = {x: 10, y: 20};

Here, obj is an object.

But wait... Technically, both arrays and functions, and many other values, are objects in JavaScript as well. So what's the distinction between a plain object and these other objects?

Well, what we've created here is called a plain object, specifically. A plain object, as the name suggests itself, is an object as well. But it's the simplest of all objects in JavaScript.

An 'object' is a generic term used to refer to any value that is not a primitive. A plain object is a more specific term that refers to the simplest of objects in JavaScript.

Plain objects are handy when we want to store multiple pieces of information under one name.

A good example would be to model a URL using a plain object. Each characteristic of the URL would go as a property in the object, such as its protocol, domain name, path and so on.

Consider the following code where we model the URL https://www.codeguage.com/ using a plain object called url:

var url = {
   protocol: 'https',
   domain: 'www.codeguage.com',
   path: '/'
};

The object has three properties:

  1. protocol — specifies the protocol of the URL, that is whether it is served over http or https.

  2. domain specifies the domain name of the URL.

  3. path specifies the path after the domain name.

Let's now access these.

We could access a property of an object using either of two ways: bracket notation or dot notation.

In the former i.e bracket notation, we write the name of the property as a string within a pair of brackets ([]) following the object value. In the latter, we write the name of the property after a period character (.) following the object value.

Below we access the protocol property on our url object in both these ways:

url.protocol'https'

url['protocol']

'https'

As you might know, ther are some characteristics of a URL that we have left out in this model. These include its query string and hash. Let's add these to our url object.

We could add a new property to an exisiting object using either of the same two options mentioned before to access a property i.e. bracket notation or dot notation. The only addition required here is that we assign a value to the property using the equals sign (=), just as we do for variables.

Consider the following code:

var url = {
   protocol: 'https',
   domain: 'www.codeguage.com',
   path: '/'
};

// add two new properties
url.queryString = null;
url['hash'] = null;

Here we add two properties to url after it has been created and stored in memory using both the given notations.

Since the URL being modeled (i.e. https://www.codeguage.com/) doesn't have a query string or hash in it, we set the respective properties queryString and hash to null.

Let's check the values of these newly added properties:

url.queryStringnullurl.hashnull

Perfect! Just as we wrote them.

Apart from these simple properties, an object could also have methods on it. Methods are special cases of properties.

A method is a property of an object that has a function as its value.

Creating methods is nothing special. We create them just like we create properties on objects. After all, methods are also properties!

The only difference between the two is that instead of assigning a string, number, Boolean, or any other value to a method, we assign it a function. This makes the property callable, and consequently, a method.

Let's define a method on the url object we created above. We'll call it getURL. This method will return back the complete URL formed by concatenating the properties given in the url object:

var url = {
   protocol: 'https',
   domain: 'www.codeguage.com',
   path: '/',

   // return the full URL, as a string
   getURL: function() {
      return url.protocol + '://' + url.domain + url.path;
   }
};

With the method in place, let's now call it:

url.getURL()'https://www.codeguage.com/'

Since a method is technically a function, we call it using the same syntax employed while calling a function i.e. a pair of parentheses (()) at the end of the expression.

As with simple object properties, we could call the getURL() method using bracket notation as well:

url['getURL']()

'https://www.codeguage.com/'

And this is it for objects!

We'll dive into the complex world of objects and object-oriented programming (shortened as OOP) in the JavaScript Objects unit, where we will learn tons and tons of concepts related to objects.

Last updated