Junior — Middle
Can you list ways to use the Object construct in JavaScript?
sobes.tech AI
Answer from AI
In JavaScript, the Object construct is used in several main ways:
- Creating objects:
const obj1 = new Object();
const obj2 = {};
- Declaring properties and methods:
const obj = {
name: 'Alice',
greet() { console.log('Hello'); }
};
- Using static Object methods:
Object.keys(obj)— returns an array of the object's keys.Object.values(obj)— returns an array of the object's values.Object.assign(target, ...sources)— copies properties from sources to the target object.Object.freeze(obj)— makes the object immutable.
- Property checking:
if (Object.hasOwn(obj, 'name')) { /* ... */ }
- Setting the prototype:
const proto = { greet() { console.log('Hi'); } };
const obj = Object.create(proto);
obj.greet(); // Hi
Thus, Object is a fundamental building block for working with objects in JavaScript.