DEV Community

Cover image for Let's explore Objects Methods in JavaScript
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

Let's explore Objects Methods in JavaScript

Objects in JavaScript are collections of Key/Value pairs. The values can consist of properties and methods. This post will go over important built-in object methods.

Object.create()

Used to create a new object and link it to the prototype of an existing object.

const person = {
     isHuman: false,
     printIntroduction: function() {
          console.log('My name is ${this.name}. Am I a human? ${this.isHuman}')
     }
}

const me = Object.create(person)

me.name = 'Mursal'
me.isHuman = true

me.printIntroduction()
// Expected Output: "My name is Mursal. Am I a human? true"
Enter fullscreen mode Exit fullscreen mode

Object.keys() and Object.values()

Object.keys(): Creates an array containing the keys of an object
Object.values(): Creates an array containing the values of an object

const num = {
     one: 1,
     two: 2,
     three: 3
}

console.log(Object.Keys(num)) // ['one', 'two', 'three']
console.log(Object.Values(num)) // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Object.entries()

Used to create a nested array of the key/value pairs of an object

const num = {
     one: 1,
     two: 2,
     three: 3
}

console.log(Object.entries(num))

/*
     Expected Output
     [['one', 1], ['two', 2], ['three', 3]]
*/
Enter fullscreen mode Exit fullscreen mode

Object.assign()

It is used to copy values from one object to another.

const name = {
     firstName: 'Mursal',
     lastName: 'Furqan'
}

const details = {
     job: 'Software Engineer',
     country: 'Italy'
}

// Merge the object
const character = Object.assign(name, details)

console.log(character)

/* 
     Expected Output
     {
          firstName: 'Mursal',
          lastName: 'Furqan',
          job: 'Software Engineer',
          country: 'Italy'
     }
*/
Enter fullscreen mode Exit fullscreen mode

Object.freeze()

Prevents modification to properties and values of an object, and prevents properties from being added or removed from an object

const user = {
     username: 'mursalfurqan',
     password: 'thisisalwayssecret'
}

// Freeze the object
const newUser = Object.freeze(user)

newUser.password = '*******************'
newUser.active = true

console.log(newUser)

/* 
     Expected Output
     { username: 'something', password: 'thisisalwayssecret' }
*/
Enter fullscreen mode Exit fullscreen mode

Object.seal()

Prevents new properties from being added to an object, but allows the modification of existing properties.

const user = {
     username: 'mursalfurqan',
     password: 'thisisalwayssecret'
}

// Seal the object
const newUser = Object.seal(user)

newUser.password = '*******************'
newUser.active = true

console.log(newUser)

/* 
     Expected Output
     { username: 'something', password: '******************' }
*/
Enter fullscreen mode Exit fullscreen mode

Top comments (0)