JavaScript Object: A beginner's guide

JavaScript Object: A beginner's guide

You may have heard that everything in JavaScript is an object.

It’s absolutely okay if you’re not sure what this means or how it applies to you when you’re writing code. The purpose of this article is to help you understand what JavaScript objects are and how they work.

What are Objects?

An object in JavaScript is very similar to an object in real life. Consider this; in real life, an object, such as a car, has properties like color, model, registration number, etc. It can also drive, reverse, turn, and accelerate, among other functions. This goes to buttress the point that as objects in real life have properties and can perform certain roles, JavaScript objects are similar and can carry out specific functions as well. These “functions” associated with the JavaScript objects are actually referred to as methods.

Creating an Object in JavaScript: Object Literals

Let’s take a quick look at this JavaScript code:

//create user one
var userOneName= 'Oluwaseun';
var userOneEmail='oluwaseun@gmail.com';
var userOneFriends=['jane'];

//create user two
var userTwoName= 'Mary';
var userTwoEmail='mary@gmail.com';
var userTwoFriends=['anna', 'david'];

//create user three
var userThreeName= 'Mark';
var userThreeEmail='mark@gmail.com';
var userThreeFriends=['ayo', 'luke'];

function login(email){
console.log(email, 'is now online');
}

function logout(email){
console.log(email, 'has logged out');
}

function logFriends(friends){
    friends.forEach(friend => {
      console.log(friend)
})
}

In the code above, we're creating numerous variables to store various user data. We have “userOneEmail”, “userOneFriends”, “userTwoEmail”, “userTwoFriends”, and so on. You’ll also see functions like “login”, “logout”, and “logFriends”. The problem with this code is that as the project grows in size, we'll end up with what is known as spaghetti code – basically implying that the code is unstructured. At some point, that will become unmanageable and untidy. This is where JavaScript objects come in. Instead of having to write the code this way, we could group a user, all of its properties, and methods (functions) into a single variable. This variable stores information about the user in what is known as an object.

We do this by declaring the variable – say, userOne – and then creating an "object literal." We create an object literal by opening and closing curly braces like this "{}".

var userOne ={};

What we have in the code above is an empty object.

Now we can add various properties and methods to this object – such as what it means to be a user or what features the user offers. Let's say we want to store a user property called “name”. This is how we store it:

var userOne ={
    name: 'Oluwaseun',
};

This syntax for writing object properties is sometimes referred to as "key-value" pairs. In this case, "name" is the key, and "Oluwaseun" is the value.

we can also store other properties of the user, like this:

var userOne ={
    name: 'Oluwaseun',
    email:'oluwaseun@gmail.com',
    friends:['jane']
};

What we're doing here is known as encapsulation. It means we collect everything related to a user and store it in a single piece or object. We're encapsulating what it means to be a user inside an object, and now, any type of properties or functions that describe this user will live inside that object.

This is good because we're organizing our code in a much more meaningful and logical manner. We know that if we need anything related to this user, we'll find it in this single object rather than in multiple variables as it was in the previous code. We also saw the login, logout, and logFriends functions in the code we started with. These functions (or methods) can also be added to the user object. Let's see what that would look like:

var userOne ={
    name: 'Oluwaseun',
    email:'oluwaseun@gmail.com',
    friends:['jane'],
    login: function({
      console.log(this.email, 'is now online');
}
};

(I'll get to the meaning of the "this" keyword shortly.)

This way of writing methods in an object is acceptable. However, we can simply shorten it (thanks to ES6) as follows:

var userOne ={
    name: 'Oluwaseun',
    email:'oluwaseun@gmail.com',
    friends:['jane'],
    login(){
      console.log(this.email, 'is now online');
}
};

Still using “userOne” as a case study, we can write the object this way:

var userOne ={
    name: 'Oluwaseun',
    email:'oluwaseun@gmail.com',
    friends:['jane'],
    login(){
      console.log(this.email, 'is now online');
},
    logout(){
      console.log(this.email, 'has logged out');
},
    logFriends(){
      console.log(this.friends);
},
};

This is how we create an object with its properties and methods in JavaScript. Next, we’ll look at how to work with objects.

Working With Objects: Accessing object properties and methods, Upadating properties.

How to access object's properties and methods:

There are two ways you can access object’s properties and methods:

  • Dot Notation(.): This is the most common approach for accessing an object's properties and methods. We do this by first writing the name of the object variable. Next, we include the period (.) sign, and lastly, we add the property name (otherwise known as "key").
console.log(UserOne.name) //result: Oluwaseun

For the methods:

console.log(UserOne.login()) //result: oluwaseun@gmail.com is now online
  • Bracket Notation []: This is another way to access the values of the object. e.g console.log[userOne['name]']. The result will be the same "Oluwaseun"

So, this is how we access object properties and methods.

Setting and Updating Properties:

var userOne ={
    name: 'Oluwaseun',
    email:'oluwaseun@gmail.com',
    friends:['jane']
};

userOne.hobbies=['reading', 'swimming'] //this will create a new property in userOne object.

console.log(userOne) // result: {  name: 'Oluwaseun', email:'oluwaseun@gmail.com', friends:['jane'], hobbies:['reading', 'swimming']}

//the code shows how to set new property in an object.
var userOne ={
    name: 'Oluwaseun',
    email:'oluwaseun@gmail.com',
    friends:['jane']
};

userOne.name='Emmanuel'// this will update the name of the user to 'Emmanuel"
console.log(userOne)// result: { name: 'Emmanuel', email:'oluwaseun@gmail.com', friends:['jane']
};

//the code shows how to update the property of an object.

The 'this' keyword

Still considering our old pal “userOne”:

var userOne ={
    name: 'Oluwaseun',
    email:'oluwaseun@gmail.com',
    friends:['jane'],
    login(){
      console.log(this.email, 'is now online');
}
};

The keyword "this" basically refers to the object in which it was written. In our case study, "this" refers to the userOne Object. Depending on where it is placed in your code, “this” can hold different meanings. For instance, if the keyword “this” is contained within an object, it will refer to that object. If it is placed outside of the object, "this" will refer to JavaScript's global "window" object built into JavaScript. When a method's context changes, 'this' always ensures that the correct values are used. For example;

var userOne ={
    name: 'Oluwaseun',
    email:'oluwaseun@gmail.com',
    friends:['jane'],
    login(){
      console.log(this.email, 'is now online');
}
};

var userTwo ={
    name: 'Mary',
    email:'mary@gmail.com',
    friends:['anna', 'david'],
    login(){
      console.log(this.email, 'is now online');
}
};

userOne.login(); // result: Oluwaseun, is now online
userTwo.login(); // result: Mary, is now online

Even when we used "this.name" in both objects, we got different results – Oluwaseun and Mary. It is highly used when we dynamically create objects.

Additonal Notes

Most things – not everything – are objects in JavaScript. Null, numbers, Booleans, and strings are examples of non-objects in JavaScript. Since they are not objects, you cannot access a property or method. In JavaScript, they are all referred to as primitive types.

However, non-objects, such as strings, can be made to behave like objects in JavaScript. This happens when JavaScript wraps them into an object in the background. (I’ll cover this in a different article.)

We’ll be drawing the curtains on the basics of JavaScript objects here. This is enough to get you started. Please upvote and share this post if you enjoyed it. You can also check out my work by following me on [GitHub].(github.com/AboladeOluwaseun).