How to clone a portion of an object using the power of IIFE, arrow functions, destructuring assignment and property shorthands.
Tags: javascript, webdev
Published: 2019-07-16 13:59:50

---
title: How to clone a portion of an object using the power of IIFE, arrow functions, destructuring assignment and property shorthands.
published: true
description: How to clone a portion of an object using the power of IIFE, arrow functions, destructuring assignment and property shorthands.
tags: javascript, webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/ua883ygz2blehkdgq8gj.jpg
---

**Our goal**
Let's say we want to create a new object inheriting only a few `property:value` from another, but not all. Just like the following:

![](https://thepracticaldev.s3.amazonaws.com/i/aqch53gpdhrgjphb0p32.png)

**What's the best way to accomplish this**? Well, there are several available, but the most powerful and concise one is /w doubt the following:

![](https://thepracticaldev.s3.amazonaws.com/i/bfgjbdgdahufsp1uwim2.png)

What you see is a **an immediately invoked anonymous arrow function (IIFE) that accepts an object, destructs its properties and return them as a new object**.

Sounds complicated? Well, let's break it down then.

---

## Immediately Invoked Function Expression (IIFE)

An Immediately Invoked Function Expression is a way to execute functions
immediately, as soon as they are declared. IIFEs are an excellent solution since they don't pollute the global object and are a smart way to isolate variables declarations. (_Thanx to [Flavio Copes](https://flaviocopes.com/) for this exceptional explaination_)

The basic form of an IIFE is the following:

``` javascript
;(function() {
  // The code we want to execute immediately.
})()

// No need to call this funcion after.
```

Now, since we want the code inside the IIFE to perform operations on an object, we need to inject the original object into it, in order to make it available throughout the entire IIFE scope:
``` javascript
// Our original object.
const person = { name: "Luca", lastName: "Grandicelli", age: 39 }

// Let's inject 'person' into the IIFE
;(function() {
  // The object 'person' is now available here.
})( person )
```

> _The ';' at the beginning of the IIFE help us to prevent issues when concatenating two JavaScript files. Since the language does not require semicolons, you might concatenate with a file with some statements in its last line that causes a syntax error._

---

## Arrow functions

Arrow functions are probably one of the most appreciated changes by the JS dev community since their introduction in ES6/ECMAScript 2015. They basically tranform the old function declaration:

``` javascript

// The old way
const foo = function myFunction( param1, param2 ) {
/* */
}

// The new way
const foo = ( param1, param2 ) => {
/* */
}
```

**Pay attention**: Arrow functions do treat the `this` keyword in a different way we're used to, so they do not completely substitute the old syntax, which is still valid especially in context such as class & objects methods or event callbacks.

However, their power lies in the way they can be extremely concise:

``` javascript

/*
* When the function body contains only a single statement, you can omit the
* parentheses and put everything on a single line, such as:
*/
const foo = () => doSomething()

// Of course, you can pass parameters too:
const foo = ( param1, param2 ) => doSomething( param1, param2 )

// ...but if you have only one parameter, you can just omit the parentheses completely:
const foo = param => doSomething( param )

```

Another great property is the **Implicit Return**:

``` javascript
/**
* When there's an in-line statement in the function body, you can return values
* without using the return keyword:
*/
const foo = () => 'my value'
foo() // Returns 'my value'

/**
* You can return an object too. Just remember to wrap the curly brackets in
* parentheses to avoid it being considered the wrapping function body brackets:
*/
const foo = () => ({ value: 'my value' })
foo() //Returns { value: 'my value' }
```

Quite cool ain't it? Ok, now let's combine IIFE /w arrow functions:
``` javascript
// Let's cast some magic spell here...
;(() => {
/* */
})( person )
```

Good. Now move on and let's check out how we can extract properties from an object.

---

## Destructuring assignment

[From the MDN Webdocs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment):
> _The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables_.

Let's start /w an example:

``` javascript

/**
* We want to create two variables called 'a' and 'b'
* and fill them /w the first two elements of the 'list' array.
*/
const list = [1, 2, 3, 4, 5]
const [ a, b ] = list
console.log( a ) // Prints 1
console.log( b ) // Prints 2

/**
* Same thing, we can use objects too.
* In this case, we have to use the same property names as variables.
* This allow us to extract multiple properties regarless of their order.
*/
const list = { a: 1, b: 2, c: 3, d: 4, e: 5 }
const { a, c } = list

console.log( a ) // Prints 1
console.log( c ) // Prints 3
```

Destructuring assignment is especially useful when we need to pass an object as parameter of a function and then extract values from it. So let's apply this concept to our initial code, combining IIFE + arrow functions + destructuring assignment:


``` javascript

// Our original object.
const person = { name: "Luca", lastName: "Grandicelli", age: 39 }

/*
* Let's destructure the original object properties 'name' and 'age'
* into two separate variables in the function args declaration.
* Then return a new object with those props as values.
*/
;(({ name, age }) => {

  // Build & return the new object.
  return { name: name, age: age } // Equals to: { name: "Luca", age: 39 }
})( person )
```

## Properties shorthand

In JavaScript ES6/ECMAScript 2015, if you want to define an object who's keys have the same name as the variables passed-in as properties, you can use the shorthand and simply pass the key name:


``` javascript

// Let's declare some variables here.
var name = 'Luca';
var lastName = 'Grandicelli';
var age = 39;

/**
* Old pre-ES6 syntax:
*/
var myObject = {
  name : name ,
  lastName : lastName ,
  age : age 
}

/**
* ES6/ECMAScript 2015 syntax
*/
const myObject = {
  name,
  lastName,
  age
}

// ...or...
const myObject = { name, lastName, age }
```

And here we come to the end of this article. Let's sum up eveything and combine IIFE + arrow functions + destructuring assignment + properties shorthand:

``` javascript
// Our original object.
const person = { name: "Luca", lastName: "Grandicelli", age: 39 }

/**
* Now let's apply the property shorthand to our returning object,
* since its keys names equals the value names.
*/

// Our IIFE function.
;(({ name, age }) => {
  return { name, age } // Equals to: { name: "Luca", age: 39 }
})( person )

// Since the above function is one-only return statement, everything becomes:
;(({ name, age }) => ({ name, age }))( person )

// ... and finally:
const luca = (({ name, age }) => ({ name, age }))( person )
```

There are, however, several ways to accomplish this task; this is just an example of how powerful Javascript can be.

If you want to know more about the topics discussed in this article, follow these links:

**Arrow Functions**
[MDN Webdocs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
[ES6 Arrow Functions Cheatsheet](https://dev.to/samanthaming/es6-arrow-functions-cheatsheet-1cn)
[A tutorial to JavaScript Arrow Functions](https://flaviocopes.com/javascript-arrow-functions/)

**IIFE - Immediately Invoked Function Expression**
[MDN Webdocs](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)
[Wikipedia](https://en.wikipedia.org/wiki/Immediately_invoked_function_expression)
[Essential JavaScript: Mastering Immediately-invoked Function Expressions](https://medium.com/@vvkchandra/essential-javascript-mastering-immediately-invoked-function-expressions-67791338ddc6)

**Destructuring assignment**
[MDN Webdocs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
[ES6 Destructuring: The Complete Guide](https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f)

**Properties shorthand**
[MDN Webdocs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
[Object Property Value Shorthand in JavaScript with ES6](https://alligator.io/js/object-property-shorthand-es6/)