Skip to content

Latest commit

 

History

History
114 lines (85 loc) · 4.73 KB

A04-spread-rest-operator.md

File metadata and controls

114 lines (85 loc) · 4.73 KB

Credit: javascript.info, freecodecamp.org

Exercise

Spread & Rest Operator

The spread and rest operators actually use the same syntax: ...

Yes, that is the operator - just three dots. It's usage determines whether you're using it as the spread or rest operator.

Using the Spread Operator:

The spread operator allows you to pull elements out of an array (=> split the array into a list of its elements) or pull the properties out of an object. Here are two examples:

const oldArray = [1, 2, 3];
const newArray = [...oldArray, 4, 5];
// This now is [1, 2, 3, 4, 5];

Here's the spread operator used on an object:

const oldObject = {
	name: 'Max'
};
const newObject = {
	...oldObject,
	age: 28,
}

newObject would then be

{
	name: 'Max',
	age: 28
}

The spread operator is extremely useful for cloning arrays and objects. Since both are reference types (and not primitives), copying them safely (i.e. preventing future mutation of the copied original) can be tricky. With the spread operator you have an easy way of creating a (shallow!) clone of the object or array.

Destructuring

Destructuring allows you to easily access the values of arrays or objects and assign them to variables.

Here's an example for an array:

const array = [1, 2, 3];
const [a,b] = array;
console.log(a); // prints 1
console.log(b); // prints 2
console.log(array); // prints [1, 2, 3]

And here for an object:

const myObj = {
	name: 'Max',
	age: 28,
}
const { name } = myObj;
console.log(name); // prints 'Max'
console.log(age); // prints undefined
console.log(myObj); // prints {name: 'Max', age: 28}

Destructuring is very useful when working with function arguments. Consider this example:

const printName = (personObj) => {
	console.log(personObj.name);
}
printName({name: 'Max', age: 28}); //prints 'Max'

Here, we only want to print the name in the function but we pass a complete person object to the function. Of course this is no issue but it forces us to call personObj.name inside of our function. We can condense this code with destructuring:

const printName = ({name}) => {
 console.log(name);
}
printName({name: 'Max', age: 28}); // prints 'Max'

We get the same result as above but we save some code. By destructuring, we simply pull out the name property and store it in a variable/ argument named name which we then can use in the function body.

Resources:

Exercises