Objects are the collection of key/value pairs that can be modified throughout the lifecycle of an object as similar to hash map or dictionary. Objects allow us to define custom data types in JavaScript.
Unlike primitive data types, we can represent complex or multiple values using objects. The values can be the array of objects or the scalar values or can be the functions. Data inside objects are unordered, and the values can be of any type.
An object can be created by using curly braces {...} along with an optional properties list. The property is a "key:value" pair, where the key is a string or a property name, and the value can be anything.
There are two syntaxes to create an empty object:
var user = {}; // 'object literal' syntax var name = new Object(); //'object constructor' syntax
Similar to primitive data types, objects also have a literal syntax. Object literal is one of the widely used patterns to create objects in JavaScript.
ES6 makes the object literal more concise and robust by extending the syntax in different ways.
Let us see the shorthand for object property initializer.
Before ES6, the object literal is a collection of name-value pairs. For example,
In ES5
function user(name, division) { return { name: name, divison: division }; }
The above function user() takes two arguments, which are name and division, and returns a new object literal having two properties name and division. The property name and division take the values of the function parameters.
The above syntax looks repetitive because the name and division mentioned twice in keys and values of properties.
The syntax in ES6 eliminates the duplication when an object property is the same as the name of a local variable. Let's understand this by rewriting the above user() function in ES6.
In ES6
function user(name, division) { return { name, divison }; }
In the above code snippet, the JavaScript engine assigns the value of name and division arguments to the name and division properties.
Similarly, we can construct an object literal by local variables, as shown in the following example:
let uname = 'Anil', udivision = 'First'; let user = { uname, udivision }; console.log(user.uname); console.log(user.udivision);
By using this shorthand syntax, the JavaScript engine looks in the scope for a variable with the same name. If it is found, then the value of the variable is assigned to the property. But if it is not found, then a reference error will occur.
Before ES6, we could use the square brackets [] to enable the computed property names for the object properties. Square bracket notation allows us to use variables and string literals as the name of the property.
ES6 introduced a new feature 'computed property names,' which is a part of object literal syntax, and it uses the square bracket [] notation. It allows us to put an expression within the square brackets [] that will be computed and used as the name of the property.
Let us understand computed property names by using the following example:
var emp = { id : 101, name : 'Amit' } var department = 'dep_name'; emp[department]='Sales'; console.log(emp);
In ES6
var department = 'dep_name'; var emp = { id : 102, name : 'Anil', [department]:'Production' } console.log(emp);
Before ES6, defining a method for an object literal, we must have to specify the name and definition of a complete function as represented in the following example:
let user = { firstName : "Sunil", lastName : "Kumar", fullName : function(){ return this.firstname + " " + this.lastName; } };
ES6 uses shorthand syntax, which is also known as the concise method syntax for making a method of the object literal concise by removing the colon (:) and the function keyword.
Let's use this syntax on the above example by rewriting the object user.
let user = { firstName : "Sunil", lastName : "Kumar", fullName(){ return this.firstname + " " + this.lastName; } };
It is possible to merge two JavaScript objects in ES6 by using two methods, which are listed below:
Let us try to understand these two methods.
This method is used for copying the values and properties from one or more source object to a target object. It returns the target object, including properties and values copied from the target object.
Object.assign(target, sources)
var obj1 = {1 : "Hello", 2: "World"}; var obj2 = { 3 : "Welcome", 4: "to"}; var obj3 = { 5 : "rookienerd"} // Using Object.assign() var final_obj = Object.assign(obj1, obj2, obj3); console.log(final_obj);
Cloning is the process of copying an object from one variable to another variable. We can clone an object by using the object.assign() method.
Let us try to understand it with the following example:
let obj1 = { name: 'Anil', age: 22 }; let cloneobj = Object.assign({}, obj1); cloneobj.age = 32; console.log(obj1); console.log(cloneobj);
It is widely used in a variable array where multiple values are expected. As the objects in JavaScript are key-value paired entities, we can merge them into one by using the spread operator.
var new_obj = [...obj1, ...obj2, ...]
var obj1 = {1 : "Hello", 2: "World"}; var obj2 = { 3 : "Welcome", 4: "to"}; var obj3 = { 5 : "rookienerd"} var final_obj = {...obj1, ...obj2, ...obj3}; console.log(final_obj);
It can be possible to remove or delete a property by using the delete operator. Let us understand how to remove a property by using the following example.
var obj = new Object; obj.a = 50; obj.b = 200; delete obj.a; console.log (obj.a);
It is similar to array destructuring except that instead of values being pulled out of an array, the properties (or keys) and their corresponding values can be pulled out from an object.
When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.
To learn more about object destructuring, you can click on this link ES6 Object destructuring.