DEV Community

Himanshu Gupta
Himanshu Gupta

Posted on • Updated on

JavaScript Most important Thing! Object

Image description

Object-Oriented Programming is actually a programming paradigm that tells you to divide your code into a different objects, and those objects contain fields and methods. When I say fields, I basically mean variables and when I say methods, I basically mean functions that can be connected to each other and you can change the data that is inside them as well.

JavaScript objects are similar to objects in real life which consist of different attributes and properties. These objects are defined as an unordered collection of related data, that are of primitive or reference types. These are defined in the form of “key: value” pairs.

Add a Key/Value pair to an Object in JavaScript

  • Use bracket [] notation, e.g. obj['name'] = 'John'.
  • Use dot . notation, e.g. obj.name = 'John'.
  • Use the Object.assign() method, passing it a target and source objects as parameters.

`Let’s look at an example using the first 2 ways.


const obj = {name: 'Tom'};
obj.age = 30;
obj['country'] = 'Chile';
// 👇️ {name: 'Tom', age: 30, country: 'Chile'}
console.log(obj);

We first add a key/value pair using dot . notation. It is more concise and direct than the bracket [] notation approach.

If a key with the supplied name already exists on the object, its value will get overridden.

However, if the name of the key in your object has spaces or contains a dash -, you have to use the square brackets approach.

const obj = {name: 'Tom'};
obj.my-country = 30; // 👈️ SyntaxError
obj['my-country'] = 'Chile'; // 👈️ Works
`
You also use the square brackets approach when you don’t know the name of the key in advance and you need to dynamically name the key.
`

const obj = {};
const key = 'city';
obj[key] = 'Santiago';
// 👇️ {city: 'Santiago'}
console.log(obj);

In the code snippet, we have the name of the key stored in a variable, therefore we can’t use dot notation to set the key/value pair on the object.

Notice that we don’t wrap the value between the square brackets in quotes, because it is a variable, whose value we use for the key.

As a general rule of thumb, you will see most programmers use dot . notation to add key/value pairs to objects, unless they have to use the square brackets [] approach.

The next most common way to add a key/value pair to an object is using the Object.assign method.

To add multiple key/value pairs to an object in the same statement, use the Object.assign() method. The method copies the key/value pairs of one or more objects into a target object and returns the modified target object.

const obj = {country: 'Chile'};
Object.assign(obj, {color: 'red', food: 'pizza'});
// 👇️️ {country: 'Chile', color: 'red', food: 'pizza'}
console.log(obj);

The parameters we passed to the Object.assign method are:

the target object — the object to which the provided properties will be applied
the source object(s) — one or more objects that contain the properties we want to apply to the target object
A straight forward way to think about the Object.assign method is that the key/value pairs of the object we passed as the second parameter get copied into the object we provided as the first parameter.

The Object.assign method is very convenient when you have to add multiple key/value pairs to an object.

Another common approach to add multiple key/value pairs to an object is to use the spread operator (...). However, notice that to use the ... syntax, we declare the variable using the let keyword.

let obj = {name: 'Tom'};
obj = {...obj, color: 'green'};
// 👇️ {name: 'Tom', color: 'green'}
console.log(obj);

An easy way to think about the spread operator (…) is that we are unpacking the key/value pairs of the object into a new object.

We use the let keyword instead of const because it allows us to re-declare the obj variable.

We basically create a new object, using the key/value pairs of an existing object and some additional ones.

Rename an Object’s Key in JavaScript #
To rename the key of an object, use bracket notation to assign the value of the old key to the new key, e.g. obj['newKey'] = obj['oldKey']. Then use the delete operator to delete the old key - delete obj['oldKey']. The object will contain only the key with the new name.

const obj = {oldKey: 'value'};
obj['newKey'] = obj['oldKey'];
delete obj['oldKey'];
console.log(obj); // 👉️ {newKey: 'value'}
We used bracket [] notation to assign the value of oldKey to the newKey property in the object.

The last step is use the delete operator to delete the old key from the object.

This practically renames the key in the object.

If the names of the keys in the object don’t contain spaces or start with special characters, you can also use dot notation.

const obj = {oldKey: 'value'};
obj.newKey = obj.oldKey;
delete obj.oldKey;
console.log(obj); // 👉️ {newKey: 'value'}

This code snippet achieves the same goal and is a bit cleaner. However, some of the limitations that exist when accessing object properties with dot notation, don’t exist when using bracket [] notation.

An alternative, but also very common approach is to use the Object.assign method.

const obj = {oldKey: 'value'};
delete Object.assign(obj, {newKey: obj.oldKey})['oldKey'];
console.log(obj); // 👉️ {newKey: 'value'}
The Object.assign method takes 2 parameters:

the target object — the object to which the sources’ properties are applied
the sources — the source objects that contain the properties to be applied to the target object.
The method returns the target object with the provided properties applied.

We added the newKey property on the object and set it to the value of the oldKey property.

The last step is to use the delete operator to delete the oldKey property.

Get the Length of an Object in JavaScript #
To get the length of an object, pass the object to the Object.keys() method and access the length property, e.g. Object.keys(obj).length. The Object.keys method returns an array containing the object's keys, which can be used to determine the object's length.

const obj = {country: 'Chile', city: 'Santiago'};
const length = Object.keys(obj).length;
console.log(length); // 👉️ 2
We used the Object.keys method to get an array of the object’s keys.

The only parameter the method takes is the object, for which the keys are returned.

The last step is to access the length property on the array to get the number of key-value pairs in the object.

An alternative approach is to initialize a length variable, set it to 0 and use a for...in loop to iterate over the object.

const obj = {country: 'Chile', city: 'Santiago'};
let length = 0;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
length += 1;
}
}
console.log(length); // 👉️ 2

The for...in loops iterates over the object's enumerable properties, including the inherited ones.

This is why we had to use the Object.hasOwnProperty method to check if the property exists directly on the object or is inherited.

We only increment the length variable if the property exists directly on the object.
Check if a Value is an Object in JavaScript #

To check if a value is an object:

Verify the value has a type of object — typeof variable === 'object'.
Verify the value is not null — variable !== null.
Verify the value is not an array — !Array.isArray(variable).
If all conditions pass, the value is an object.

const variable = {name: 'Tom'};
if (
typeof variable === 'object' &&
variable !== null &&
!Array.isArray(variable)
) {
console.log('✅ Value is an object');
} else {
console.log('⛔️ Value is not an object');
}

We used the logical AND (&&) operator to chain 3 conditions in our if statement.

All conditions have to pass for our if block to run.

The first condition uses the typeof operator to check if a value has a type of "object".

The typeof operator returns a string that indicates the type of a value. Here are some examples.

console.log(typeof {}); // 👉️ "object"
console.log(typeof []); // 👉️ "object"
console.log(typeof null); // 👉️ "object"
console.log(typeof function () {}); // 👉️ "function"
console.log(typeof (() => {})); // 👉️ "function"
console.log(typeof ''); // 👉️ "string"
console.log(typeof 0); // 👉️ "number"

Notice that an array and a null value also have a type of "object". To make sure the value does not store an array or null, we have to add 2 additional checks.

Our second condition checks that the value is not equal to null.

And the third — that the value is not an array.

If all of the conditions pass, we can conclude that the value is an object.

All of the following 3 types have a value of object:

an object literal {}
an array []
a null value
An alternative approach is to use the prototype property on the Object class.

// 👇️ true
console.log(Object.prototype.toString.call({}) === '[object Object]');
// 👇️ false
console.log(Object.prototype.toString.call([]) === '[object Object]');
// 👇️ false
console.log(Object.prototype.toString.call(null) === '[object Object]');

We called to toString() method on the prototype, passing it an object, an array and null.

The names of all 3 are different when stringified:

// 👇️️ "[object Object]"
console.log(Object.prototype.toString.call({}));
// 👇️ "[object Array]"
console.log(Object.prototype.toString.call([]));
// ️👇️ "[object Null]"
console.log(Object.prototype.toString.call(null));

This makes it a viable solution because we don’t have to chain 3 conditions to get the result. However, I still prefer the first approach because it is more readable and intuitive.

I try to avoid “magic” strings like [object Object] as much as possible, because they are prone to errors and difficult to debug.

Top comments (0)