Important JavaScript Object Methods

Actions that can be taken on objects are called methods in JavaScript. A property that has a function declaration is a JavaScript method. The functions that are saved as object properties are called methods.

This technique can be helpful to find out more details about an object or make sure it has access to another object’s prototype.

Object.keys()

An easy method for returning all of an object’s keys after iterating over the item.

const employee = {
    name: 'John',
    age: 35,
    occupation: 'Developer',
    level: 7
};

console.log(Object.keys(employee));

//Output:
['name', 'age', 'occupation', 'level']

Object.values()

returns the values of the object after iterating over it!

const employee = {
    name: 'John',
    age: 35,
    occupation: 'Developer',
    level: 7
};

console.log(Object.values(employee));

//Output:
['John', 35, 'Developer', 7]

Object.entries()

returns an object’s individual enumerable string-keyed property [key, value] pairs.

const drinks = {
    apple: 30,
    orange: 45
};

for (const [name, cost] of Object.entries(drinks)) {
    console.log(`${name}: ${cost}`);
}

//Output:
apple: 30
orange: 45

Object.create()

uses an existing object as the model for the newly formed object to be constructed.

let emp1 = {
    name: 'John',
    display() {
        console.log('Name:', this.name);
    }
};

let emp2 = Object.create(emp1);

emp2.name = 'Denis';
emp2.display();

//Output:
Name: Denis

Object.assign()

the target object receives a copy of all enumerable and own properties from the source objects. It gives back the desired object. Additionally known as a shallow copy.

const target = {
    a: 1,
    b: 2
};

const source = {
    b: 4,
    c: 5
};

const returnedTarget = Object.assign(target, source);

console.log(target);
console.log(returnedTarget);

//Output:
{a: 1, b: 4, c: 5}

Object.seal()

By sealing an object, all existing attributes are designated as non-configurable and no new properties can be added to it.

const laptop = {
    price: 55000
};

Object.seal(laptop);
laptop.price = 60000;
console.log(laptop.price);

//Output:
60000
//Value changed successfully. Now we delete it.

delete laptop.price;

console.log(laptop.price);

//Output:
60000

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories