Objects
We will learn about new methods, functionality, and syntax improvements added to objects in ES2015.
We'll cover the following...
Static object methods
Arrays and strings are not the only data structures that have gained new functionality. Objects have received several new methods and improvements as well. Let’s briefly look at the most important ones:
Object.assign(target, source[ source[...,],])
The Object.assign()
method is the most useful addition because it enables merging one or more objects into an existing object and returns the result as an object. But beware: the existing object is mutated. Hence, you should use this method sparingly. Following is an example to illustrate the point:
const user = { id: 1, name: 'Manuel' };const modifiedUser = Object.assign(user, { role: 'Admin' });console.log(user);console.log(modifiedUser);console.log(user === modifiedUser);
The role
property of the object in the second parameter of the Object.assign()
function is added to the existing destination object.
React embraces the principle of pure functions, which are functions that are encapsulated in themselves and do not modify their entry parameters.
Taking this into account, it becomes apparent that such mutations should be avoided if possible. We can circumvent this problem by providing an empty object literal as the first argument:
const user = { id: 1, name: 'Manuel' };const modifiedUser = Object.assign({}, user, { role: 'Admin' });console.log(user);console.log(modifiedUser);console.log(user === modifiedUser);
By providing a newly created ...