Modern Javascript part 3 : destructuring, spread operator, and ES6 object enhancements illustration
Javascript

Modern Javascript part 3 : Spread operator, destructuring, and ES6 object enhancements

Hello guys! In this new article, we continue to explore the modern Javascript with really useful features : The spread operator, destructuring, and ES6 object enhancements. Clone, merge,… play with array and objects become a child’s play!

Basics with spread operator

First, what is the spread operator? To answer, it is written ... and its interest is to extract some values of arrays or objects.

You can clone an object or array like :

const initialObj = {
  someValue: 'a',
  orherValue: 'b'
};

const cloneObj = { ...initalObj };
// Now, cloneOjb equals initialObj but has´nt the same reference

const initialList = ['a', 'b'];

const cloneList = [ ...initialList ];
// clone list is a new array with 2 value 'a' and 'b'

Moreover, you can use it to merge to objects/arrays. For example :

const arrayOne = ['a', 'b'];
const arrayTwo = ['c', 'd'];

const merged = [ ...arrayOne, ...arrayTwo ];
// The result will be ['a', 'b', 'c', 'd']

Now, let’s use the spread operator with an object :

const objOne = {
  a: 'test',
  b: 'test1',
};

const objTwo = {
  a: 'another test',
  c: 'test1',
};

const merged = { ...objOne, ...objTwo };
// The result will be : {a: "another test", b: "test1", c: "test1"}

As you can see, the property a of the first object has been erased by the property with the same key, in the second object. So, be careful of the order of your merge when you use the spread operator.

Play with objects!

With those new syntaxes, you can do lot’s of new things, like create objects with conditional keys. Consider the following code :

const ADMIN = 0;
const WRITER = 1;
const MEMBER = 2;
const GUEST = 3;

const getUserPrivileges = userRole => ({
  add: false,
  update: false,
  remove: false,
  read: false,
  ...(userRole === ADMIN ? { add: true, remove: true, update: true, read: true } : {}),
  ...(userRole === WRITER ? { add: true, update: true, read: true } : {}),
  ...(userRole === MEMBER ? { read: true } : {})
});

In this case, ADMIN user has all rights, WRITER can update, read, and add, but not remove. And a MEMBER can only read.

It’s a stupid example, I let you imagine all you can do.

Dynamic object keys

It’s new useful ES6 object enhancement. Her, the ES5 way :

var obj = {
  someKey: 'value'
};
var keyName = 'dynamicKey';

obj[keyName] = 'value';

But in ES6, you can directly do that :

const keyName = 'dynamicKey';
const obj = {
  someKey: 'value',
  [keyName]: 'value',
}

Destructuring assignment

First, with the destructuring, you can dynamically create variables from arrays or object. And with an array :

const [firstName, lastName] = "Kévin Dumont".split(' ');

console.log(firstName); // Kévin
console.log(lastName); // Dumont

with an object :

const user = {
  firstName: 'Kévin',
  lastName: 'Dumont',
};

const { firstName, lastName } = user;

console.log(firstName); // Kévin
console.log(lastName); // Dumont

And the destructuring works too with sub-objects :

const app = {
  loggedInUser: {
  	firstName: 'Kévin',
  	lastName: 'Dumont',
  },
  // ... other
};

const getHelloMessage = name => 'Hello ' + name + '!';

const { loggedInUser: { firstName } } = app;

alert(getHelloMessage(firstName)); // Hello Kévin!

And, last case : imagine the user is a guest. You can specify a default value for its firstName. Let’s take a look at this example :

const app = {
  loggedInUser: {
    // Empty user
  },
  // ... other
};

const getHelloMessage = name => 'Hello ' + name + '!';

const { loggedInUser: { firstName = 'Stranger' } } = app;

alert(getHelloMessage(firstName)); // Hello Stranger!

Important note : In all of the previous destructuring cases, the initial array or object won’t be affected!

That’s it for spread operator and destructuring. Soon, the next part of my Javascript courses. Thank your for reading!

Previous parts :