Objects in JavaScript

Objects in JavaScript

ยท

7 min read

In javascript, Most of the things are Objects. So having a grip over this concept is very necessary. In this guide, we are going to learn about objects, how it is created, used, and more. Let's get started ๐Ÿ”ฅ

What is an Object?

According to Mozilla developer's guide, An object is a collection of related data and/or functionality. Basically, It consists of some key-value pairs that we call Properties. We can also store methods or functions inside objects.

Let's see how it looks and how we create an object -

var user = {
   firstName: 'Harshad',
   lastName: 'Mehta',
   age:45,
   hobbies:['winning','driving Lexus'],
     isLion : true,
   message: function(){
      return `${this.firstName} says Lala!!!`
   }
}
console.log(user) //this will return all the object values 
console.log(user.message()) // this will run the function message inside the user object

Creating Object and Its Properties

  • We will now create a student object and the object's syntax is that all the key and value pairs are separated by commas and enclosed by the object literals i.e, curly braces { key: value, key: value }.
// Creating object for storing student details

const student = {
    studentName: "Bunny",
    studentRollNo: 7,
    studentCourse: "JavaScript",
    presentAttendance: true   
}

How to access the object's properties:

  • Dot Notation(.) โ‡’ This is what we used in that example to run the message function inside the user object. we access the values of properties in the object by using dot(.) after the key name. for example - we can get the age of the user in the previous example by doing console.log(user.age). This will give 45 as the result.

  • Bracket Notation [] โ‡’ This is another way to access the values of the object. e.g.console.log(user['age']) this will give the age of the user that is 45.

  • Variables in objects are called properties. Here, student is an object and its properties are studentName, studentRollNo, studentCourse and presentAttendance We can access the properties of an object in two different ways.

        // First way: Using Dot notation, a convenient and preferred way.
        // To print the name of student
        console.log(student.studentName); 
    
        // Below Output will be:
        Bunny
    
        //Second way: Using Square notation.
        console.log(student['studentName']);
    
        // It will also print the same output:
        Bunny
    
  • Objects can be assigned a new property and updated. It means that Objects are mutable. In objects, the existing value can also be replaced with a new value. Let's test this now.

const student = {
    studentName: "Bunny",
    studentRollNo: 7,
    studentCourse: "JavaScript",
    presentAttendance: true,   
    }  

// Creates a new property in the student object
student.studentMarks = 90;

//Assigns a new value on an existing property 'presentAttendance'
student.presentAttendance = false;

// Removes RollNo property in the object;
delete student.studentRollNo

// Printing Object
console.log(student);

// Below Output: An updated 'student' object
{
  studentName: 'Bunny',
  studentCourse: 'JavaScript',
  presentAttendance: false,
  studentMarks: 90
}

Let's breakdown what's going on here.

Here we created an object name user and we stored all the properties inside {} brackets. For each property, we provide a key name and value for that, separated by a : colon ( in this case, firstName: 'Harshad'). And finally, all the properties are separated by , comma.

An Object can have properties of any data type, as we can see in the example, It has a string, number, boolean, array. Even we had a function in an object, which is called object methods.

Nesting objects โœจ:

In the previous example, we could have also made a nested object instead of an array for hobbies. e.g.

//This is how we nest objects  
var user = {
   firstName: 'Harshad',
   lastName: 'Mehta',
   age:45,
   isLion : true,
   hobbies:{
      firstHobby:'Winning',
      secondHobby:'Driving Lexus'
   },
   message: function(){
      return `${this.firstName} says Lala !! `
   }
}
// accessing nested object.
console.log(user.hobbies.firstHobby) // Winning
console.log(user['hobbies']['firstHobby']) //Winning

Set and update object members:

var user = {
   firstName: 'Harshad',
   lastName: 'Mehta',
   age:45,
   isLion : true,
}

user.age = 55;
user.isLion = false;
console.log(user.age) //55
console.log(user.isLion) //false

I hope you go the idea of what is happening here, pretty straight-forward.

We can also set the new members by doing the same thing, e.g.

var user = {
   firstName: 'Harshad',
   age:45,
}
user.luckyNumber = 5; //this will create a new property in user object
console.log(user) //{ firstName: 'Harshad', age: 45, luckyNumber: 5 }

Different Methods Of Creating Object

Object.assign() Method

  • The syntax of object.assign() method is

        Object.assign(target, sources)
    

The Object.assign () copies all enumerable and own properties from one or more source object to the target object. It returns the target object. The word here, enumerable means countable and the property can be viewed if it is looped through.

// Created object 'object1'
const object1 = {
    name: 'Riya'
}

// The target object is the already created object 'object1'.
// The source object is holding the key value pairs in object literals.

Object.assign(object1, {
    name: 'new Riya',
    tech: 'Javascript'
})

// Returns the target object with updated properties.
console.log(object1)

// Below output:
{ name: 'new Riya',
 tech: 'Javascript' }
  • The above code has no specifically mentioned source object, just created using object literals to copy the data and pass it to the target object. We have modified the existing object.
// Created object 'object1'
const object1 = {
        name: 'Riya'
    }

// Created object 'object2'    
const object2 = {
    tech: 'Javascript'
}

// Created object 'object3'
// Target object: 'object3' 
// Source object: 'object1', 'object2'
const object3 = Object.assign({}, object1, object2, {
    database: 'MongoDB'
})

// Below Output
console.log(object1);
{ name: 'Riya' }

// Below Output
console.log(object2);
{ tech: 'Javascript' }

// Below Output
console.log(object3);
{ name: 'Riya',
 tech: 'Javascript',
 database: 'MongoDB' }
  • The source objects were object1 and object2 which were not modified and the target object object3 had both source objects' properties.

Object.defineProperty() Method

  • The syntax of object.defineProperty() method is
Object.defineProperty(obj, prop, descriptor)
  • If you check the below code, you will agree that we can define a property dot notation, right?

        const object1 = {}
        object1.name = 'Riya'
    
  • Now, let's do the same thing using Object.define() property.

// Created object1
const object1 = {};
// Using defineProperty
Object.defineProperty( object1,'name', {
    value: 'Riya'
})
  • The first code and the second one, both are the same but then what is the difference between both?

  • In the first type, we can not restrict the modification if we want to modify the value of the name. However, in the second one, let's not talk but do.

const object1 = {};

Object.defineProperty( object1,'name', {
    value: 'Riya',
    writable: false
})

object1.name = 'Riya modify'

// Below Output:
console.log(object1.name)
Riya
  • Notice, we define the property just like the first case but later we change the value of the property as 'Riya modify' and print the value but it is not changed. This happened due to the attribute defined writable: false for this. It could restrict the modification and the value is still the same. So, it is a kind of advanced method, we can say.

What is 'this' keyword :

We have seen in the first example that we returned the firstName inside message function referring this.firstName. Basically, 'this' refers to the object itself in which it is written. In our example, this refers to the user object.

'this' is very useful โ€” it always ensures that the correct values are used when a member's context changes. e.g.

var user1 = {
   name: "Harshad",
   age: 45,
   message: function () {
      return `${this.name} says Hii`;
   },
};
var user2 = {
   name: "John",
   age: 30,
   message: function () {
      return `${this.name} says Bye`;
   },
};
console.log(user1.message()); // Harshad says Hii
console.log(user2.message()); // John says Bye

Even we used ${this.name} in both the objects, but we get different results i.e. Harshad and John respectively. It is highly used when we dynamically create objects.

Conclusion

So, this article was just a small chuck of objects of which we covered almost basics. There is still one method object.create() which will be covered in the next article since there will be a concept of prototype understanding for this.

I hope, you found this article helpful to skim through the basics which are always important in our javascript journey. Till then, Happy Coding, and stay tuned for the next article, See you!


ย