Need to Know JavaScript Concepts - Lesson #6

Understanding Objects and Arrays in JavaScript

Understanding Objects and Arrays in JavaScript

Ever seen some data in square brackets and curly brackets in JavaScript? These are Arrays and Objects respectively.

// arrays

// objects

We will be discussing Objects and Arrays in JavaScript. You probably know data types in JavaScript such as:

  • String
  • Number
  • Boolean
  • Null
  • Undefined

Objects and Arrays are no different, but have a little more complex data structure. They can be visualized as containers for other datatypes in JavaScript, thus the term: data structures.

A JavaScript Object is similar to a natural object you know; for example, a cup, a house, a car etc.

These objects can:

  • contain several things
  • have unique features
  • can contain other objects
  • can be used for several purposes
  • be able to accept several actions done on them

For example, a cup can have a smaller cup in it, drinking water from a cup, breaking a cup, driving a car, putting a kid or a toy car in a car and the list goes on.

JavaScript Objects are no different, only that they look like this:

const myObject = {};

The curly brackets denote the object and elements in the Object make up the object. Object values come in Key: Value pairs and these values can either be properties of the object or methods (functions). Properties are features or attributes of the Object, whereas methods are functions or actions that can be performed on the Object.

Note: Object methods have to be defined in the object in order to be usable or recognized by the object.

Objects are represented as such:

const myObject = {
    myKey1: 'ObjectValue1',
    myKey2: 'ObjectValue2',
    mykeyN: 'ObjectValueN',
    objectMethod: function() {
      // Do something on this object

Basically, almost everything in JavaScript is an Object. For this reason, JavaScript is seen as an object-oriented language by many. In the browser, once a window loads, an instance of the Document object is created and every other thing displayed on the browser is a child of the document object and document methods are used to manipulate the parent object.

Objects can also be nested:

const myObject = {
  first:  { key:  'thing', key2: 2 },
  second: { key3: 'otherThing' }, 
  third:  { key4: 'my string' }

When we say everything is an object, that means that JavaScript wraps all of types with an object that provides methods for that type. To clarify this, let's look at the following code:

// create a message with a string value
const myMessage = 'look at me go!';

// convert to uppercase

How were we able to call a method .toUpperCase() on this string? We usually are only able to call methods on objects. When we create a string, JavaScript actually wraps that string with the object of type string. The following is the same

// simple way to create a string
const myMessage = 'look at me go!';

// what javascript sees
const myOtherMessage = String('look at me go!');

myMessage == myOtherMessage; // true

There are a few ways to create objects:

This is done as shown above by placing the key: value pairs and methods in curly brackets. This is also known as literal notation.

const obj = {
    firstName: 'William',
    lastName:  'Imoh',
    married:   true,
    greet:     function() {
      alert("Hello everyone, i'm " + this.firstName);

From the code above, we can access these properties and methods by calling:

obj.firstName;   // William
obj.lastName;    // Imoh
obj.greet();     // Will alert, Hello everyone, i'm William 

You may wonder why we used this in our code instead of obj.firstName. Well, this serves like a pronoun that refers to the parent object in which it is called. We will learn more about this in the next lesson.

This involves creating an object instance using the new keyword:

const house     = new Object();

house.color     = 'red';
house.houseType = 'bungalow';
house.location  = 'Lagos';

All we did was create an object instance, assign it to the variable house, then edit its properties and their individual values.

Also, a function constructor can be used to make the creation of objects or multiple similar objects easier.

function University(name, location, size) {     = name;
  this.location = location;
  this.size     = size;

const theUniversity = new University('caritas', 'enugu', 20000);;     // caritas
theUniversity.size;     // 20000

Here, a function was constructed with arguments. Notice that the function name is in Capital case which is a convention for constructor functions. The function is passed arguments, these arguments are the primary values of the object’s properties as defined by

A new Object is constructed with the new keyword calling the function and passing it parameters matching the parameters defined in the function. Run this;


and we get this:

University {
  name:     'caritas',
  location: 'enugu',
  size:     '20000'

The properties of Objects can be accessed in two ways using:

In the dot notation, the value of an object’s property is accessed as thus:

const objectName = {
  objectProp: 'my super duper value',

objectName.objectProp; // my super duper value

The square bracket notation is an alternative to the dot notation and is written as such:

const objectName = {
  objectProp: 'super cool yo!',

objectName['objectProp']; // super cool yo!

In cases where the property name starts with a special character like a dash or a number, or you'd like to use a variable as the key, the square bracket notation can only be used.

Since the beginning of modern programming languages, using the for-loop to traverse data sets has been priceless, in Objects, there are a number of ways to traverse or iterate through object properties and they are:

  • for…in loop: This is the most common one and is used to iterate over each enumerable property of the object and its prototype chain.
  • Object.keys(o): The object.keys(o) method is used to traverse an object o and returns an array containing all enumerable property names.
  • Object.getOwnPropertyNames(o): A lesser known method, it iterates over an object o and returns an array of all natural property names of the object, enumerable or not.

Arrays are a special kind of JavaScript Object.

const a = [];

typeof a; // returns object

Arrays are data structures that take in multiple variables, singularly say, 300 chickens! Unlike the Object data structure, they do not have the key: value pairs but singular data in them. How do you identify an array? It looks like this:

const myArray = ['hi', 'i', 'am', 'chief'];

The data in arrays are enclosed by square brackets and can contain as many variables as you want as well as other arrays. Arrays are objects and can contain objects too.

const myArray = [
  { name: 'chris', location: 'racoon city' }

Arrays are created in two ways:

Using the array literal is the most common way of creating arrays. Array values are enclosed in square brackets.

const arr = [];
const bar = ['drinks', 'music', 'dance', 'beer', 'more beer'];

// an array of objects
const coocoo = [
  { key:  'thing', key2: 2 },
  { key3: 'otherThing' }, 
  { key4: 'my string' }

This is another way of creating arrays using the new keyword, it is considered bad practice by many as it could bring about unforeseen behaviors in your script. The array values are passed as arguments to the constructor.

const bar = new Array('beer', 'music', 'beer', 'more beer');

console.log(bar);  // ['beer', 'music', 'beer', 'more beer']

In cases like:

const fig = new Array(10, 20);

console.log(fig);   // [10, 20]

What if a figure is removed? We have:

const fig = new Array(10);

console.log(fig);   // returns 10 empty arrays!

We get 10 empty arrays! Using the array literal [] is always advised as it's more readable, requires less writing, and behaves how we'd expect.

Unlike objects, array values are accessed using their index position starting from zero (arrays are zero-indexed). Objects use lettered indexes while arrays use numbered indexes. Arrays are accessed like this:

const myArr = [10, 40, 50, 70, 20, 2, 100];

myArr[0] // 10
myArr[3] // 70
myArr[7] // 100

Trying to use lettered indexes on an array such as arr.firstNumber will throw an error message.

Just like Objects, arrays also have methods which can be used to manipulate them. These methods are built-in or can be constructed. There are several array methods and they can be found here.

const fig = [2, 5, 10, 30, 20];

arr.length;   // returns the length of the array = 5

Iterating over an array is quite seamless using the for-loop. Using the above example:

const fig = [2, 5, 10, 30, 20];

for (let i = 0; i < fig.length; i++) {

// 2
// 5
// 10
// 30
// 20

Other array methods include:

  • pop(): removes the last element from an array and returns that element
  • slice(): returns a shallow copy of a portion of an array into a new array
  • shift(): removes the first element from an array and returns that element
  • unshift(): adds one or more elements to the beginning of an array and returns the new length of the array

When looking to work with arrays, always look to the built-in methods. You'll usually find what you need there.

Array methods can be grouped into mutator methods, accessor methods and iteration methods. Mutator methods are those methods that actually alter or modifies the array, for example, the array.push() method adds a specified element to an array and returns the modified array.

const fig = [10, 20, 30, 40];

console.log(fig);    // [10, 20, 30, 40, 80]

Accessor methods are those that do not alter the array but rather create an image of the array based on the effect of the method, for example array.slice()

const fig = [10, 20, 30, 40];
const b   = fig.slice(1);

console.log(b);      // [20, 30, 40]
console.log(fig);    // [10, 20, 30, 40]

Iteration methods as the name implies are used to iterate over an array while sampling the length of the array and evaluating each element of the array with a callback function as defined in the method. This includes .forEach() and .map() methods.

const fig = [10, 20, 30, 40];

const newFig = { //calls a function on each element of the array
  return val + 10;

console.log(newFig) // [20,30,40,50]

Lastly, arrays have properties which include the length and arrays can have objects created in them.

We clearly understand what objects are, how they can be created, what makes them special by handling properties and values. Objects have various applications ranging from database architecture to server responses.

An array, on the other hand, is a collection of data more like in a container. Its uses are also vast. Feel free to play around with the numerous methods available to both arrays and objects and always remember that they usually go hand in hand. Many times you'll be creating an array of objects; for example, you may have a list of user objects.