A beginner's guide to Objects in JavaScript

comfortdeola

Adeola Ajiboso

Posted on May 10, 2023

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!

💖 💪 🙅 🚩
comfortdeola
Adeola Ajiboso

Posted on May 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related