DEV Community

Cover image for A beginner's guide to Objects in JavaScript
 Adeola Ajiboso
Adeola Ajiboso

Posted on • Edited on

A beginner's guide to Objects in JavaScript

Introduction

JavaScript is a popular programming language that is commonly used in web development. As a newbie in JavaScript, you may have come across the term objects and wondered about its significance.

However don't fret, because in this article, we'll talk about objects in a fun and easy-to-understand method. We'll also look at some code samples to better understand the concept of objects.

Specifically, we will explore object-oriented programming, object methods, prototypes, inheritance, constructors, and classes.

Let's dive into the topic at hand!

What are Objects in JavaScript?

Objects in JavaScript refer to a group of properties. Properties consist of key-value pairs, where the key is represented by a string, and the value can be of any data type, including another object. In JavaScript almost anything can be treated as an object, and each object can contain properties with values. In simple terms, objects are like Rockstar's of JavaScript - they come in style, save the day, and organize your data like a boss.

Let’s consider the example below:

// object literals syntax
const person = {
  firstName: "Adeola";,
  lastName:"Comfort";,
  age: 19;,
  country: 'Nigeria';
};
Enter fullscreen mode Exit fullscreen mode

In this example, person is an object with four properties and values respectively:

  • firstName - Adeola
  • lastName -Comfort
  • age-19
  • country- Nigeria

Accessing Objects Properties

Accessing objects in JavaScript can be compared to gaining entry to a vault filled with valuable data, where the key to unlock the vault is the object property. There are two ways to access an object's properties, using either dot notation or bracket notation.
Let’s consider the example below using the dot notation:

// accessing object value using the dot notation
console.log(person.firstName) // output: Adeola
Enter fullscreen mode Exit fullscreen mode

Let’s consider the example below using the bracket [] notation:

//using [] to access object value
console.log(person['age'])
Enter fullscreen mode Exit fullscreen mode

In this example, the person['age'] returns the value of the age property, which is 19.

Objects Method

Methods are actions that can be performed on objects. Methods are still functions, but it's defined on an object.

Let’s consider the example below, creating an object method:

// object literals syntax
const person = {
  firstName: "Adeola",
  lastName:"Comfort",
  age: 19,
  country: 'Nigeria',
  fullname: function(){
console.log(`Hello, my full name is ${this.firstName} ${this.lastName}`)
};
};
person.fullname()
output: //Hello, my full name is Adeola Comfort 
Enter fullscreen mode Exit fullscreen mode

In JavaScript, this keyword is a context object representing the context in which the current code is executed.

Getters and Setters

Getters are used to access objects' properties, and setters are used to change or mutate them.
Let’s consider this example of getters:

//Getters
const person = {
  firstName: "Blue",
  lastName: "Doe",
  occupation: "Writer",
  get job() {
    return this.occupation;
  }
};
console.log(person.occupation) // Output: Writer
Enter fullscreen mode Exit fullscreen mode

Let’s consider this example of setters:

//object literals syntax
   const person = {
   firstName: "John",
   lastName: "Doe",
   occupation: "NO",
   set lang(value) {
        this.occupation = value;
      }
    };
    person.lang = "Software Developer";
    console.log(person.occupation)      
//Output: Software Developer
Enter fullscreen mode Exit fullscreen mode

Object.entries

The Object.entries() method converts an object into an array of key-value pairs.

Let’s consider the example below to understand Object.entries() better:

//Object literals
const user = {
  name: 'Zoe',
  age: 4,
  color:  'Blue',
  email:'zoe@gmail.com'
};

// object.entries
console.log(Object.entries(object1))

/* output
 we have a subarray of a key and value pair
[
  [ 'name', 'Zoe' ],
  [ 'age', 4 ],
  [ 'color', 'Blue' ],
  [ 'email', 'zoe@gmail.com' ]
]
*/
Enter fullscreen mode Exit fullscreen mode

Object.keys

Object.keys return an array of the object's property name. For example, Let’s consider the code below to understand Object.keys:


const user = {
  name: 'Zoe',
  age: 4,
  color:  'Blue',
  email:'zoe@gmail.com'
};
console.log(Object.keys(user))

/*output
 we have the array of those property name
[ 'name', 'age', 'color', 'email' ]
*/
Enter fullscreen mode Exit fullscreen mode

Object.values

Object.values return an array of the object values. Let’s consider the example below:


const user = {
  name: 'Zoe',
  age: 4,
  color:  'Blue',
  email:'zoe@gmail.com'
};
console.log(Object.values(user))

/* output
[ 'Zoe', 4, 'Blue', 'zoe@gmail.com' ]
*/
Enter fullscreen mode Exit fullscreen mode

Object-Oriented Programming(OOP) In JavaScript

Object-oriented programming is a programming paradigm centered around objects rather than functions.

OOP is not a programming language rather, it's a style of programming.

In JavaScript, objects are used to model real world , giving them properties. For instance, think of a laptop: a laptop has object properties such as make, model, operating system(OS), RAM specification, etc., and methods like on(), off(), etc.

Objects can be defined using factories or constructor functions. Creating an object with the object literal syntax is an issue only if the object has behaviors.

Constructor

Constructor functions are used to create new objects with specific properties and methods. Object-oriented programming often uses them to create multiple instances of an object with the same properties and methods.

Let’s consider the example of an object constructor function:

function Person(name, interest) {
  this.name = name;
  this.interest = interest;
  this.greet = function() {
    console.log("Hello, my name is " + this.name + " and  I love " + this.interest);
  }
}

// create new objects from the constructor
let person1 = new Person("John", "Slepping"); 
let person2 = new Person("Jane", "Writing");

//access properties in the created object
person1.greet(); //Output:Hello, my name is John and  I love Slepping
person2.greet(); //Output:Hello, my name is Jane and  I love Writing
Enter fullscreen mode Exit fullscreen mode

In creating a constructor, the naming convention we use for constructor function is different, the first letter should be uppercase.

In the above example, we define a Person constructor function that takes two parameters, name and interest. Inside the constructor function, we use the this keyword to create properties on the newly created object. We then create two instances of the Person object using the new keyword and passing in the appropriate parameters.

When we access the properties in the created object person1.greet andperson2.greet`, we see that they contain the expected values as shown in code snippet above.

In the above example, we define a Person constructor function that takes two parameters, name and interest. Inside the constructor function, we use the this keyword to create properties on the newly created object. We then create two instances of the Person object using the new keyword and passing in the appropriate parameters.

When we access the properties in the created object person1.greet and person2.greet`, we see that they contain the expected values as shown in code snippet above.

Prototype

Every object in JavaScript has a prototype property that allows for object inheritance. The prototype property is an object that acts as a template or blueprint for creating new objects.

When a property or method is called on an object, JavaScript first looks for that property or method directly on the object itself. If it can't find the property or method on the object, it looks to the object's prototype property for the property or method. If the property or method still can't be found, it looks up the prototype chain until it reaches the end of the chain, which is the Object.prototype object.

Let’s consider the example below:

// create the constructor
function Students(name, age, grade) {
  this.name = name;
  this.age = age;
  this.grade = grade;
  this.register = function() {
    console.log("Hello, " + this.name + " you have been registered");
  }
}
// creating a method using the prototype keyword
Students.prototype.greet = function() {
  console.log("Hello, my name is " + this.name + " and I'm " + this.age + " years old.");
}
// generate new objects from the constructor
let person1 = new Students("July", 30); 
let person2 = new Students("Jane", 35);

person1.register(); // "Hello, July you have been registered"
person2.register(); // "Hello, Jane you have been registered"

person1.greet(); // "Hello, my name is July and I'm 30 years old."
person2.greet(); // "Hello, my name is Jane and I'm 35 years old."
Enter fullscreen mode Exit fullscreen mode

The given code defines a constructor function named Students. The constructor function takes three parameters (name, age, and grade) and assigns them as properties of the newly created object using the this keyword. It also defines a method called register() that logs a message to the console, welcoming the student by their name and letting them know they have been registered.

Then, using the prototype property of the constructor function, it defines another method called greet(). The greet() method logs a message to the console, introducing the student by their name and age.

Finally, the code creates two instances of the Students object, person1 and person2, by using the new keyword and passing in the appropriate values for each student's properties.
When the register() method is called on each object, it logs a welcome message to the console. Similarly, when the greet() method is called on each object, it logs an introduction message to the console.

Classes

In JavaScript, classes provide a way to define a blueprint for creating objects with similar properties and methods. Classes are syntactical sugar over the existing prototype-based inheritance system in JavaScript.

Here's an example of how to create a class in JavaScript:

//create the  class constructor
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log("Hello, my name is " + this.name + " and I'm " + this.age + " years old.");
  }
}
const student2 = new Person('Adeola', '30')
console.log(student2)
Enter fullscreen mode Exit fullscreen mode

Inheritance

Inheritance refers to an object's ability to inherit properties and methods from a parent object. Inheritance is implemented in JavaScript classes by using the extends keyword to create a child class that inherits from a parent class.

The idea behind inheritance is code reusability. Inheriting from the Parent class makes the Child class able to use all the methods and properties of the parent class.

Here's an example of how to create a Person class with a child class that inherits from it:


// create the constructor
class Person {
  constructor(name, age, grade) {
    this.name = name;
    this.age = age;
    this.grade = grade;
  }

  greet() {
    console.log("Hello, my name is " + this.name + " and I'm " + this.age + " years old.");
  }
}
class Student extends Person {

  study() {
    console.log(this.name + " is studying hard for his " +  this.grade + ' grade');
  }
}
const student1 = new Student("John", 18, '12th');

student1.greet(); // Output: "Hello, my name is John and I'm 18 years old."
student1.study(); // Output: "John is studying hard for his 12th grade."
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, understanding object is essential for web development. By knowing what an object entails and how its applicable, developers can write more efficient and effective code.

To be clear, I'm not an expert on these topics. I'm simply sharing what I've been taught and learning along the way. I hope you've gained some knowledge.

Resources

I highly recommend you check out the following resources, which cover the concepts explained further:

Do not hesitate to ask questions or leave comments on this post. I'm available on Twitter, LinkedIn, or GitHub. Keep an eye out for my upcoming blog post, in which I'll go over another important area of web development. As a developer, I'm glad to provide additional information. Until then, happy coding, and take care!

Top comments (16)

Collapse
 
desoga profile image
deji adesoga

Awesome article. Welcome done! Keep up the good work.

Collapse
 
comfortdeola profile image
Adeola Ajiboso

Thank you😊

Collapse
 
desoga profile image
deji adesoga

You're welcome.

Collapse
 
efpage profile image
Eckehard • Edited

There is one thing about objects in Javascript, that might cause confusion.

As mentioned, a group of key:value-pairs is called an object:

    const person = {
      firstName: "Adeola",
      lastName: "Comfort"
    };
Enter fullscreen mode Exit fullscreen mode

"objects" may have a nested structure like this:

    const human = {
      person: {
        firstName: "Adeola",
        lastName: "Comfort"
      },
      age: 23
    };
   console.log(typeof(human))  --> "object"
Enter fullscreen mode Exit fullscreen mode

So, "object" is oviously a structured datatype.

So, where do "classes" come from?

Initially, Javascript had no classes, it featured a so called "prototype based" inheritance.
Classes have been introduced in languages like C++ or Object Pascal more than 30 years ago, and they used the name "object" already, but with a different meaning. A class gives you only a "blueprint" of an object. To get a working element, you need to build an "instance" of this class. This was called an object. You may have many objects of the same type (=class). To avoid any conflicts, each object has it´s own set of private variables that is usually well protected. They can only be accessed from the outside, if you explicitely define them as "public". This "encapsulation" is very important to keep object oriented code running.

Over the last years, Javascript was heavily influenced by this concept, so a "class based inheritance" was introduced in ES5:

    class humanClass {
      firstName = "Adeola"
      lastName = "Comfort"
    }
    let human = new humanClass
    console.log(typeof (human)) --> "object"
Enter fullscreen mode Exit fullscreen mode

Ok, we still have an "object", but wait: the syntax is quite different! Above, we defined key:value pairs, here we define a variable, just without using let or var.

The designers of javascript tried to make things as consistent as possible, but on the same time follow the rules of class bases inheritance. Finally, they did a good job, but it might also seem, that "objects" and "objects" do not have much in common.

One bad thing about javascript objects is, that they are not encapsulated. As class based objects behave the same like standard objects, all variables can be mutated from functions outside the scope of an object. Private methods and filed are introduced lately with ES2021, but they are still not implemented in all browsers,

Collapse
 
johnodh58450097 profile image
John Odhiambo

A great piece of information. Thanks for sharing with us the newbies

Collapse
 
comfortdeola profile image
Adeola Ajiboso

You welcome

Collapse
 
abdulrahmonbb profile image
abdulrahmonbb

Great piece Adeola. Nice work!

Collapse
 
comfortdeola profile image
Adeola Ajiboso

Thank you😊

Collapse
 
efpage profile image
Eckehard • Edited

Object-oriented programming is a programming paradigm centered around objects rather than functions.

Newcomers: don´t be afraid: Classes and objects are just a way to organize your code, which still is made of functions and variables. So, We should better say: With OOP you get another level of code organization ontop of your functions. Classes will help you to isolate parts of your code in better protected and resusable units.

Even if you use OOP, you are not forced to build anything as an object. It is just an option you can use where appropriate. Often, it is more work work to write OOP code, so you should use classes only where it pays back. This is often the case if you are able to reuse working code from other projects or external sources.

Collapse
 
comfortdeola profile image
Adeola Ajiboso • Edited

Thanks for the explanation

Collapse
 
krunalgupta02 profile image
Krunal Gupta

Amazing

Collapse
 
comfortdeola profile image
Adeola Ajiboso

Thank you

Collapse
 
krunalgupta02 profile image
Krunal Gupta

Hey can u make more blogs on concepts of JS if possible plz

Thread Thread
 
comfortdeola profile image
Adeola Ajiboso

Alright

Collapse
 
jonrandy profile image
Jon Randy 🎖️

...where the key is represented by a string...

Or a symbol.

Collapse
 
elijah57 profile image
Elijah Echekwu

I use python and I've been lazy to learn OOP in javascript. Looking at this article, it's almost the same as python. Thanks Adeola