DEV Community

Cover image for OPERATIONS IN OBJECTS
Vinoth Kumar
Vinoth Kumar

Posted on

OPERATIONS IN OBJECTS

OPERATIONS IN JS OBJECTS:

CHECHKING IF A PROPERTY EXISTS: You can check if an object has a property using the in operator or has OwnProperty() method.

EXAMPLE:

let obj = { model: "Tesla" };
console.log("color" in obj);
console.log(obj.hasOwnProperty("model"));
Enter fullscreen mode Exit fullscreen mode

ITERATING THROUGH OBJECT PROPERTIES: Use for.in loop to iterate through the properties of an object.

EXAMPLE:

let obj = { name: "Vinoth", age: 23 };
for (let key in obj) {
    console.log(key + ": " + obj[key]);
}
Enter fullscreen mode Exit fullscreen mode

MERGING OBJECTS: Objects can be merged using Object.assign() or the spread syntax { ...obj1, ...obj2 }.

EXAMPLE:

let obj1 = { name: "Vinoth" };
let obj2 = { age: 23};

let obj3 = { ...obj1, ...obj2 };
console.log(obj3);
Enter fullscreen mode Exit fullscreen mode

OBJECT LENGTH: Find the number of properties in an object using Object.keys().

EXAMPLE:

let obj = { name: "Vinoth" };
console.log(typeof obj === "object" && obj !== null);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)