# 👷‍♀ Desctructuring

2 min read, 345 words desctrucutingdesctructurefactory

ES6 Feature

  1. Object Destructuring
  2. Array Destructuring
  3. 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)

spread operator in react reducer

# Desctructuring in 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();

Function spread operator

# Object Desctructuring

Object Desctructuring (opens new window)

real power of destructuring

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)

Subscribe to our Newsletter

If you like my work and think it was helpful kindly support my work


Buy Me A Coffee