# 👷♀ Desctructuring
ES6 Feature
- Object Destructuring
- Array Destructuring
- In Functions
Convert bigger arrays or objects to smaller arrays and objects. Smaller workable chunks Or combining them
# Using spread Operator
to create a shallow copy
const alphabets = ['A', 'B', 'C', 'D', 'E', 'F']
const numbers = [1, 2, 3, 4, 5, 6]
// old way
cons a = alphabet[0]
// ES6 way
const [a,, c, ...rest] = alphabet
// combining Lists
const combinedArray = [...alphabet, ...numbers]
const combinedArray = alphabet.concat(numbers)
# Desctructuring in Functions
- JS functions Can not return multiple values (opens new window), but we can use destructuring and return objects and arrays from functions.
- Set default values in javascript functions?
Factory Function
When objects have logic, the produces objects
// factory function
function getValues() {
return {
first: getFirstValue(),
second: getSecondValue(),
};
}
const { first, second, third = "not defined" } = getValues();
# Object Desctructuring
Object Desctructuring (opens new window)
real power of destructuring
- Merging Objects (opens new window) Useful when designing backend API responses
- very prevalent in react and other javascript frameweorks
const someJson = {
name: "avi",
age: 30,
address: {
city: "somewhere",
state: "who knows",
},
};
const {
name: firstName,
address: { city },
...rest
} = someJson;
// combining Objects
const merged = { ...obj1, ...obj2 };
let result = { ...item, location: { ...response } };
// function Parameters
function printJson({ name, age, spouse = "none" }) {
console.log(`Name is ${name}. Age is ${age}. Spouse ${spouse}`);
}
printJson(someJson);
# Destructuring on Function Parameters
# Is destructuring performant ?
const example1 = (props) => {
const color = props.color;
return <h1 style={{ color }}>Hello</h1>;
};
const example2 = (props) => {
const { color } = props;
return <h1 style={{ color }}>Hello</h1>;
};
const example3 = ({ color }) => {
return <h1 style={{ color }}>Hello</h1>;
};
As of 2018, function destructuring on v8 seems to be more verbose (opens new window)