Introduction To JS Objects

There are 8 data types in javascript, out of which 6 are primitive (Number, BigInt, Null, Undefined, String & Boolean) and 2 are non-primitive datatypes (Objects & Symbols).

Creating an Object

We can create an object in two ways

i. Using Object Constructor

let me = new Object();

ii. Using Object Literal

let me = {};

The object contains properties(data-items like an array, string, number, etc anything except functions) and methods(functions).

Object Properties

There are 2 types of object properties

i. Data Properties

A data property contains key-value pair. Key-value pairs are separated by a comma not semi-colons inside an object. Keys are generally strings but they can be symbols as well and value can be pretty much anything. You can access data properties using either dot notation or square bracket notation.

syntax:-

let objectName = {
key1: value1,
key2: value2,
...
};
orlet objectName = {};
objectName.key1 = value1;
objectName[key2] = value2;
...

example:-

let me = {
name: 'saqib',
age: 18,
};
orlet me = {};
me.name = 'saqib';
me[age] = 18;

Data Properties besides value have 3 special attributes/features/flags.

a. Writable

If true the value of a property can be changed otherwise it is read-only.

b. Enumerable

If true then property can be listed in loops otherwise it is not listed.

c. Configurable

If true the property can be deleted and other features of the property (Writable, Enumerable, Value) can be modified otherwise not.

When we create a property a property all 3 of them are true. To check and modify these flags of an object we use the following 4 methods:-

1- Object.getOwnPropertyDescriptor()

This method returns the “property descriptor” object which contains all the attributes of the given property.

syntax:-

Object.getOwnPropertyDescriptor(objectName, propertyName)

example:-

let me = {
name: 'saqib',
age: 18,
};
Object.getOwnPropertyDescriptor(me, 'name');{value: 'saqib', writable: true, enumerable: true, configurable: true}

2- Object.getOwnPropertyDescriptors()

This method returns the property descriptor of every property of the object.

syntax:-

Object.getOwnPropertyDescriptor(objectName);

example:-

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}
}

3- Object.defineProperty()

If the property exists, this method updates its flags. Otherwise, it creates the property with the given value & flags (here if any flag is not supplied it is assumed to be false)

syntax:-

Object.defineProperty(objectName, propertyName, descriptorObject);

example:-

let me = {
age: 18,
};
Object.defineProperty(me, 'name', {value: 'saqib', writable: true, enumerable: true, configurable: true});me;
{age: 18, name: 'saqib'}

4- Object.defineProperties()

This method allows us to define (create or modify) many properties of an object at once.

syntax:-

Object.defineProperties(objectName, {
key1: descriptorObject1,
key2: descriptorObject2,
...
});

example:-

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}

ii. Accessor Properties

Accessor Properties have configurable and enumerable attributes but they don't have value and writable attributes like data properties instead they have Get & Set attributes. Accessor properties are actually functions but they seem like properties to external code. When you read data from the accessor property Get method is called and when you assign data to the accessor property the Set method is called.

syntax:-

let obj = {
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};

example:-

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

A function inside an object is called the method of that object.

syntax:-

let objectName = {
functionName: function() {...};
}
orlet objectName = {
functionName() {...};
}

example:-

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

Cloning an Object

When a variable is assigned an object it does not store it like other primitives but it stores its address in memory, in other words, a reference to it.

When an object variable is copied the reference to the object is copied not the object itself. To copy the object we need to create an actual copy of it or clone it.

We can clone an object in three ways;

  1. Using for in Loop

for-in loop iterates over all properties whose keys are strings (i.e; skipping ones whose keys are symbols) including inherited ones.

syntax:-

for (variable in object) { ..code to be executed.. };

A different property name is assigned to the variable on each iteration.

example:-

let me = {
name: 'saqib',
age: 18,
};
let clone = {};for (let key in me) {
clone[key] = me[key];
};

2. Using Object.assign() method

syntax:-

Object.assign(targetObject, source1, source2, ...);

example:-

let me = {
name: 'saqib',
age: 18,
};
let clone = {};Object.assign(clone, me);

3. Using Object.defineProperties() & Object.getOwnPropertyDescriptors()

In the normal way of cloning i.e: using for in loop or object.assign() method the modified flags are not copied and also symbolic properties are skipped. We can achieve both these things by using Object.defineProperties() & Object.getOwnPropertyDescriptors() methods together.

syntax:-

Object.definedProperties({}, object.getOwnPropertyDescriptors(sourceObjectName));

example:-

let me = {
name: 'saqib',
age: 18,
};
let clone = Object.definedProperties({}, object.getOwnPropertyDescriptors(me));

Nested Cloning

If properties have values as objects then to get rid of reference copying while cloning we do deep cloning/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]);}
}

Here we examine each me[key] and if it’s an object then we replicate its whole structure.

--

--

--

I write about Web Development, and random stuff

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

terminal

Tree Shakable Services and Lightweight Injection Tokens for optimizing Angular apps

Sharing context between tests with Cypress in 3 steps

Klara Fleischmann adds 1 more perspective to the Program Committee

@Shoot_Scope_SEO: Please check our Vimeo page https://t.co/Q4kSLcwicW

Parallel Execution in NodeJS

Testing React MobX store? Cypress made it easy!

Understanding the Shadow DOM

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
Sakib Hussain

Sakib Hussain

I write about Web Development, and random stuff

More from Medium

How to keep your Javascript projects safe -02

Week 12 — Open Source [2022/01/03]

Learn About AJAX in 4 Minutes

The Ultimate find() method in Javascript