Objects In JavaScript

Objects In JavaScript

In this article, we will cover the basics of object, its syntax, different methods of creating objects and how to create a copy of an object.

What are Objects in Javascript?

  • If you want to store a bunch of names of students then you would prefer an array. But, if you want to store the name of a student, roll number and course name, then object datatype is preferred, that’s pretty efficient in terms of memory, and also pretty fast. An object data type lets you store a collection of key and value pairs. A key can be a string and its value can be any primitive data type.

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   
}

Accessing Object's Properties

  • 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
}

Creating Method in Object

  • Functions in objects are called methods. We will add a method getMarks in the student object and access it.
const student = {
    studentName: "Bunny",
    studentCourse: "JavaScript",
    presentAttendance: false,
    studentMarks: 90,
    // Creating method 'getMarks'
    getMarks() {
        console.log(`Name of student: ${student.studentMarks}`)
    }
    // Invoking method 'getMarks'
    student.getMarks();
    // We can also create the same method in below way
    // getMarks : function (){
    //     console.log(`Name of student: ${student.studentMarks}`)
    // }
    }

Creating Nested Objects

An object can contain a bunch of objects in it and also a nested object too. Refer to this simple example below.

const student = {
        studentMarks: {
            passMarks: 40,
            failMarks: 30,
            marksGrade:{
                above80: 'A',
                below70: 'B',
                below60: 'C',
            }
        }
    }

Iteration in Object

The objects can be iterated in javascript until we meet the desired condition. It can be done using for in loops.

   const team= {
        teamMembers:{
            member1:{
                role: 'frontend',
                id: 101
            },
            member2:{
                role: 'backend',
                id: 102
            },
            member3:{
                role: 'data-analyst',
                id: 103
            },
            member4:{
                role: 'data-engineer',
                id: 104
            },
        }
    }
// Iterating through object
  for (const i in team.teamMembers){
        console.log(`${i} : ${team.teamMembers[i].role}`)  
    }
// Below Output:
member1 : frontend
member2 : backend
member3 : data-analyst
member4 : data-engineer

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.t
// 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.

Object.entries() Method

  • This method returns an array of sub-arrays which are key-value pairs in objects.
let object1 = {name:'Riya', tech: 'Javascript'}
let object2 = Object.entries(object1);
// Below Output:
console.log(object2);
[ [ 'name', 'Riya' ], [ 'tech', 'Javascript' ] ]

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!