JavaScript: Reference Data Types

JavaScript: Reference Data Types

One stop to learn and understand what a reference data type is.

ยท

10 min read

Table of contents

Reference data types are data passed by reference. An understanding of this statement is crucial throughout your career as a JavaScript developer so do well to pay close attention to the concept we are about to learn.

Consider the image below carefully.

In the image above, part A is the code you write, while part B is what happens "behind the scenes".

๐Ÿ’ก
Use the image above to follow through with the following explanation.

When you create a variable whose data type is in the reference category (e.g., object, function, array), instead of the value being directly assigned to the variable, a reference is generated for the value and that reference is what gets assigned to the variable.

The reference gets assigned to the variable, but it points to the actual value.

This means when you try to use the variable anywhere, you are working with the reference to the actual value and anything done to the reference affects the actual value.

Consider the example below;

let studentInfo = {
    name: "John Doe",
    age: 205
}

let staffInfo = studentInfo //6. This means; assign the ref of studentInfo to staffInfo

staffInfo.name = "Lorry Sante" //8. Change the value of name key in the reference which staffInfo holds.

console.log(studentInfo.name) //9. Lorry Sante
๐Ÿ’ก
Try this: Between lines 6 and 8, log the value of studentInfo.name and staffInfo.name to the console to see what they are.

You should notice that, changing name in staffInfo object (line 8), causes the name in studentInfo object to change too (as seen in the output of line 9).

In fact, both variables are pointing to the same value technically (see image below);

When we say a variable is passed by reference, it means anywhere that variable is used, you are interacting with a reference (that points) to its actual value.

So in the code snippet above, when studentInfo was assigned to staffInfo, we just made staffInfo to store a reference to the value which studentInfo points to.

Therefore, if the reference generated for studentInfo is 000xx2 and it is true that during execution, variables are replaced by whatever they hold, then staffInfo = studentInfo would become staffInfo = 000xx2 during execution, while staffInfo.name would become 000xx2.name (use the image above to understand this statement).

Think about it. If we wrote studentInfo.name, then during execution, it becomes 000xx2.name, it should be clear now that both studentInfo and staffInfo holds references to one value. They are like different roads to one destination.

๐Ÿ’ก
If this is your first time learning this concept, you should read this section again before you proceed. It will become clearer and when we start operating with reference types, you'll be glad you read this article.

There are three main reference data types that you will come across the most in your journey as a JavaScript developer;

  • Object

  • Array

  • Function

OBJECT: An object is a data structure used to store complex data in key/value pairs. The variable created in the previous session (see below) has an object type like this;

let studentInfo = {
    name: "John Doe",
    age: 205
}

You can see that it isn't primitive (simple). Unlike primitive types with just simple values, an object can be used to store different information which can be made up of even primitive and reference types.

Objects store data in key/value pairs like so; {key: value}

In the code snippet above, name is key, while "John Doe" is its value. Also, age is key, while 205 is its value.

If you notice, both name and age have primitive values (string and number).

To access the value of an object, we use the object name, dot (.) notation, and the key whose value we want to access e.g., objectName.key

Objects can also contain nested objects like so;

let studentInfo = {
    name: "John Doe",
    age: 205,
    beneficiary: {
       name: "Tira Doe",
       age: 200,
       relationship: "Wife"
    }
}

In the above example, the studentInfo object has a nested object called beneficiary. beneficiary is a key whose value is an object (reference type). Objects can still hold arrays and functions too.

Accessing the value associated with a key in an object within another object (nested object) is natural. We simply use the dot notation too. Like so parentObjectName.nestedObjectName.key

For example; to access the name of the beneficiary key in studentInfo object above, we simply write studentInfo.beneficiary.name

๐Ÿ’ก
There's no limit to how much you can nest objects in objects. Just make sure nesting is necessary for what you want to achieve and too much nesting should be avoided where necessary.

This is not all that you need to know about objects. A separate article will be dedicated to working with objects in this series. Ensure to stay alert by subscribing to my newsletter.

ARRAY: An array is a kind of object but arrays store data using automatically assigned indexes instead of keys.

An array is created by writing a comma-separated list of values enclosed with square brackets e.g [0, 1, 2, 3, "Tosin", "Mike", {name: "Abel Joe", age: 250}]

If you pay close attention to the values used in the array above, you'll notice that they are of different data types. Yes, arrays can also allow you to store values of different types in one place but this is strongly discouraged (you shouldn't do it at all). The values in an array should all be of the same type. The reason behind this best practice will become obvious as you continue your journey.

Example of a proper array: let scores = [1, 3, 5, 6, 9, 12]

To access a value in an array, we simply specify the array name, immediately followed by a square bracket [] - without any space between the name and the bracket. Then inside the square bracket, provide the index of the value you wish to access e.g arrayName[index].

What's an index and how do we know what index our value has?

An index is simply a number automatically assigned to an array value. You can think of it as an address for values in the array. Arrays are 0 indexed (meaning they start counting from zero).

To determine the index of the value you wish to access, start counting from the start of the array and your count should start from 0.

Consider the image below;

To access the value 80 in the scores array depicted in the image above, we simply write scores[3]

There is a lot we can do with arrays and trust me, you cannot be a JavaScript developer if you do not understand how arrays and objects work in-depth. So in the coming lessons, we will also dedicate an article to deal with arrays.

FUNCTION: A function is a different kind of variable and it's declared differently (using the keyword function instead of let, const or var). It is a construct used to carry out a specific task.

For example, if we need to add two numbers together at different points in our code, the best practice is to write a function once for the task and use that function whenever you need to add two numbers instead of always writing the logic to add two numbers at different points in the program. Wait!!! You are not lost. The example below will confirm this ๐Ÿ˜Š

Scenario 1 (without function):

let num1 = 2;
let num2 = 3;
let result = num1 + num2;

console.log(result) // 5

let num3 = 3;
let num4 = 8;
let result2 = num3 + num4;

console.log(result2) // 11

Scenario 2 (with function):

// function declaration.
function addNumbers (num1, num2) {
    return num1 + num2;
}

console.log(addNumbers(2, 3)); // 5
console.log(addNumbers(3, 8)); // 11

You will agree with me that scenario 2 contains less code, looks neater and even feels more natural.

Functions help us write helpers that we can call to get a specific job done for us any time we want. We just have to tell it how to do the job once and anytime we need it to do that job, we simply call it (passing in any information required for the task as arguments) and it delivers.

Function Syntax: To write a function, we use the function keyword, followed by the name of the function e.g functionName, a pair of brackets () and a pair of curly braces {}.

function functionName () {}

There are a few things/conventions you should have in mind when writing functions;

  • Function names should follow the same naming rules as variables.

  • Function names should be verbs (to depict an action).

  • The code which defines the actual task to be done should be written between the opening { and closing } curly braces.

  • If there are data required to carry out the task, they should be passed into the function as arguments and in this case, during the function declaration, parameters should be stated between the opening ( and closing ) brackets in a comma-separated fashion e.g function addNumbers(num1, num2)...

  • If no data is required to carry out the task, then the opening ( and closing ) brackets should be left empty e.g. function sayHi()...

A parameter is a variable defined between the opening ( and closing ) of a function during its declaration e.g function doSomething (param1, param2) {...}

An argument is the value passed into the function during its invocation/call e.g doSomething(1, 2)

As seen above, to call a function, simply write the function name, immediately followed by an opening and a closing bracket (without any whitespace). Required arguments should be provided between the opening and closing brackets (if any).

To drive this concept home, let's create a function to multiply two digits;

//        functionName   param1 param2
function multiplyNumbers (num1, num2) {
    return num1 * num2; // task to carry out.
}

It's as simple as that.

Having done that, let's call/invoke the function.

multiplyNumbers(2, 3) // 6
๐Ÿ’ก
Notice that while creating the function, we declared two parameters; num1 and num2, when calling the function, we supplied two arguments; 1 and 2.

RETURN keyword

Functions can return values or not.

If a function contains a return statement, like the multiplyNumbers function, then it will return a value if everything goes well. If there is no return statement for the function, it will return undefined.

function sayHi () {
    console.log("Hi");
}

If we invoke sayHi, it would log the text Hi to the console, but it will return undefined.

Remember that functions are like helpers, when you send a helper to carry out an assignment, you may require them to give you feedback (the result of the task they carried out) or you may not need feedback.

if you need feedback, add a return statement about what feedback you need. Else, do not add a return statement to the function.

We'll talk more about this when we discuss functions a bit more in-depth. There is still a lot to learn about every data type we have highlighted in this article so, just take your time to enjoy these basics and in subsequent articles, we'll go a little deeper.

SUMMARY

Reference-type variables are used to store complex data.

An array is like a toolbox, it is a single set but inside it are many other tools you can use (think of this kind of toolbox as one that stores the same type of tools in it e.g., different sizes of spanner or hammer).

I would describe an object as a book. It is a single item but inside it, there are pages, and each page may have different contents (images, text etc).

Functions are specialized helpers created to perform a certain task. We can instruct them to either return a value at the end of their operation or not.

We have succeeded in overviewing all major data types in JavaScript.
Starting from the next article in this series, we'll consider each data type deeply with examples and more real-world exercises. When we have covered all, we will begin to write more complex programs.

Please do not forget to like this post if it was helpful (you can like it up to 10 times), drop your questions or share your thoughts in the comment section, and also subscribe to my newsletter to get updates whenever I release a new episode (scroll down to find the subscribe box)**.