Introduction To JS Objects

Creating an Object

let me = new Object();
let me = {};

Object Properties

let objectName = {
key1: value1,
key2: value2,
...
};
orlet objectName = {};
objectName.key1 = value1;
objectName[key2] = value2;
...
let me = {
name: 'saqib',
age: 18,
};
orlet me = {};
me.name = 'saqib';
me[age] = 18;
Object.getOwnPropertyDescriptor(objectName, propertyName)
let me = {
name: 'saqib',
age: 18,
};
Object.getOwnPropertyDescriptor(me, 'name');{value: 'saqib', writable: true, enumerable: true, configurable: true}
Object.getOwnPropertyDescriptor(objectName);
let me = {
name: 'saqib',
age: 18,
};
Object.getOwnPropertyDescriptors(me);{
name: {value: 'saqib', writable: true, enumerable: true, configurable: true},
age: {value: 18, writable: true, enumerable: true, configurable: true}
}
Object.defineProperty(objectName, propertyName, descriptorObject);
let me = {
age: 18,
};
Object.defineProperty(me, 'name', {value: 'saqib', writable: true, enumerable: true, configurable: true});me;
{age: 18, name: 'saqib'}
Object.defineProperties(objectName, {
key1: descriptorObject1,
key2: descriptorObject2,
...
});
let me = {};Object.defineProperties(me, {
name: {value: 'saqib', writable: true, enumerable: true, configurable: true},
age: {value: 18, writable: true, enumerable: true, configurable: true}
});
me;
{name: 'saqib', age: 18}
let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
let user = {
name: "John",
get fullName() {
return this.name;
},
set fullName(value) {
this.name = value;
}
};
user.fullName; //John Smithuser.fullName = 'saqib';user.fullName; //saqib Smith

Object Methods

let objectName = {
functionName: function() {...};
}
orlet objectName = {
functionName() {...};
}
let me = {
sayHi: function() {console.log('Hi');};
}
orlet me = {
sayHi() {console.log('Hi');};
}

Cloning an Object

  1. Using for in Loop
for (variable in object) { ..code to be executed.. };
let me = {
name: 'saqib',
age: 18,
};
let clone = {};for (let key in me) {
clone[key] = me[key];
};
Object.assign(targetObject, source1, source2, ...);
let me = {
name: 'saqib',
age: 18,
};
let clone = {};Object.assign(clone, me);
Object.definedProperties({}, object.getOwnPropertyDescriptors(sourceObjectName));
let me = {
name: 'saqib',
age: 18,
};
let clone = Object.definedProperties({}, object.getOwnPropertyDescriptors(me));

Nested Cloning

let me = {
name: 'saqib',
age: 18,
him: {name: 'tajamul',age: 20,}
};
let clone = {};for (let key in me) {
if (typeof me[key] !== 'object') {clone[key] = me[key]}
else {clone[key] = {}; Object.assign(clone[key], me[key]);}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store