Objects in Javascript

Javascript is sometimes known as an object-oriented programming language. Functions, arrays, strings, numbers, boolean are all objects.

The simplest way to think of an object is something that has properties and methods. A property is like a variable that belongs to the object and a method is something the object can do or can be done to the object.

For example, an array has a property length that returns the number of items in the array. It also has methods such as the push method that adds an item to the end of an array.

const numbers = [1,2,3,4];
console.log(numbers.length);
// expected output: 4;
console.log(numbers.push(5));
// expected output: Array [1,2,3,4,5];

Storing Data with Objects

We’ve already looked at how to store data with Javascript within my Arrays in Javascript post. Javascript objects also let you store data in what is called key-value pairs. A key is kinda like a variable name and its value is like the value of that variable. In other terms think of an object as a group of variables. To create an object see the sample below.

const person = {
  name: ['Bob', 'Smith'],
  age: 32,
  gender: 'male',
  interests: ['music', 'skiing'],
};

You start by assigning the object to a variable. Then add a set of curly braces that represent an object. Remember square brackets create an array, curly braces create an object. Inside the braces, you add the property name known as the key followed by a colon to separate the key from the value. Then a value that can be any Javascript value eg a string, number, boolean and array. The property name or key doesn’t need quotes it acts as a variable name so all of the normal naming conventions apply. The white spaces around the characters are optional. To make your objects more readable its good practice to place each key-value pair on it a new line and you should indent each line two or four spaces .

Accessing Object Properties

Just like arrays objects let you store multiple pieces of information in a single variable. Arrays use a numeric index to allow you to access values and objects use keys to access properties or methods. There are two different way to access the value inside an object.

const person = {
  name: ['Bob', 'Smith'],
  age: 32,
  gender: 'male',
  interests: ['music', 'skiing'],
};

//Method One
console.log(person['name']);

//Method Two
console.log(person.name);

The first method you can use the square brackets as you do with an array but instead of giving the index number you give it the property’s name as a string. The second method is much easier and the most common method is called dot notation. You don’t need the square brackets and you don’t need to put quote marks around the property’s name. You just add a dot after the object name followed by the property name. Not only can you retrieve data this way you can set a property’s value. You just use the equals operator just as you do with simple variables.

person.age = 40; // Set value
person.location = "Belfast"; // Create Property

You can even create new properties inside and object. In our example, we’ve added a location property to our person object and assigned the value Belfast.

Objects are a package of variables. This helps keep related data grouped in one easily accessible variables. This also simplifies the handling data, for example, you can pass an object and all of its properties as a single argument to a function. It also becomes very helpful if you want to return a lot of information from a function. Remember the return keyword-only lets you return one thing if that one thing happened to be an object you return one thing full of information.

Loop through an Object

Already we’ve seen the similarities between arrays & objects. And just like you loop over an array to access its values using a loop with a numeric position. You can also access each value in an object using a special loop that only objects can use. The for-in loop runs over each key or property name in the object for example.

const person = { 
  name: Bob, 
  age: 32, 
  gender: 'male', 
  interests: music
};

for( let propName in person) { 
  console.log(propName);
  // expected output: name, age, gender, interests
}

for( let propName in person) {
  console.log(person[propName]);
  // expected output: Bob, 32, male, music
}

for( let propName in person) {
  console.log(person['name']);
  // expected output: name, name, name, name
}

The for keyword introduces the loop and we give it the person object and a variable called propName. The variable propName will refer to a property name in the object each time through the loop. The propName isn’t a keyword it’s just a variable that you name. For, let and in are the keywords and those can’t be changed. When we log the value to the console we must bracket notation. Dot notation will no work here because this would look for a property that’s is called porpName which doesn’t exist in our object. When using the bracket notation it needs a string value to access the property. Eg if we give it one of our property names it would return that properties value for every property in our object.

Array of Objects

Arrays work great when we need an ordered list of items. Objects provide a way to structure data in that’s easy to read and retrieve. It is very common to combine the two by making an array of objects.

// Multi-dimensional Array
const peopleArray = [
  ['Bob', 32],
  ['Jill', 20],
  ['Jim', 19]
];


// Array of Objects
const peopleObject = [
  {
    name: 'Bob',
    age: 32
  },
  {
    name: 'Jill',
    age: 20
  },
  {
   name: 'Jim',
   age: 19
  }
];

I’ve created an array of people and inside of that array, there are objects that contain two properties name and & age. You could’ve used another array for this data but someone looking at this code for the first time may not know what the data means. That’s one of the good things about objects they let you assign property names to identify your data. You access the data with a for a loop.

// Loop over Multi-dimensional Array 
for(let i = 0; i < peopleObject.length; i += 1 ) {
  let name = peopleObject[i][0];
  let age = peopleObject[i][1];
  console.log('Hi my name is ' + name + ' I\'am ' + age + ' years old.');
}

// Loop over Object Array
for(let i = 0; i < peopleObject.length; i += 1 ) {
  let name = peopleObject[i].name;
  let age = peopleObject[i].age;
  console.log('Hi my name is ' + name + ' I\'am ' + age + ' years old.');
}

Because the outer people variable is an array we still need to use the for loop to iterate over each value in our array. But instead of using the second bracket as you would in a multi-dimensional array we can make our code a lot easier to understand by using dot notation and passing the property name.

JavaScript Object Notation or JSON

Objects give you one location to store data that’s easy to organize and easy to access using key-value pairs. Objects do such a good job at data organization they’re used as a model for one for the webs most popular exchange formats, Javascript Object Notation or JSON. It’s used with a technology called Ajax to exchange data between a server and a web browser. There are even databases that use JSON to and receive data to update and read from a database an example of this is MongoDB. Let’s look at an example of JSON.

// https://openweathermap.org/data/2.5/weather?q=Belfast,uk&appid=b6907d289e10d714a6e88b30761fae22

{
  "coord": {
    "lon": -5.93,
    "lat": 54.58
  },
  "weather": [
    {
      "id": 803,
      "main": "Clouds",
      "description": "broken clouds",
      "icon": "04d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 6.76,
    "feels_like": 3.57,
    "temp_min": 5,
    "temp_max": 8.33,
    "pressure": 1016,
    "humidity": 81
  },
  "visibility": 10000,
  "wind": {
    "speed": 2.6,
    "deg": 20
  },
  "clouds": {
    "all": 52
  },
  "dt": 1584097506,
  "sys": {
    "type": 1,
    "id": 1376,
    "country": "GB",
    "sunrise": 1584081771,
    "sunset": 1584123810
  },
  "timezone": 0,
  "id": 2655984,
  "name": "Belfast",
  "cod": 200
}

For example, I’ve made an API call openweathermap.org that returns the weather forecast for Belfast. If you look at it closely you’ll see that it’s formatted like a Javascript Object. It opens with a set of curly braces with property names such as a name which stores the location of the weather, also properties like coord and weather that are other objects with there own properties. JSON looks just like a Javascript Object literal but it isn’t exactly. JSON is just a big string that’s made up of a series of characters, letters, numbers inside of quote marks. Once a javascript interpreter gets a hold of a JSON string it converts it to Javascript Object so it can be used with your programming like any other object.

Wrapping Up

This is a quick look at creating and accessing basic objects in Javascript. Hopefully, it helps you out with understanding them just as it did for me. You can take a look at my candidate search program to see all that we’ve covered in action on Codepen. Thank you for reading, and being part of the discussion. If you would like to chat or have any questions drop me an email I’m always happy to talk.