Skip to content

Commit 3c9fa86

Browse files
author
DouglasHdezT
committed
Add: Rest and Spread Examples
1 parent 941fd23 commit 3c9fa86

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

6-Rest&Spread/Example1.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Spread operator (...); it's used to list items inside of an Array or list attributes inside of an object;
3+
* This list can be used to complement a new array or object, copying this elements and adding the new ones declared.
4+
*/
5+
6+
const spreadArray = () => {
7+
let oldArray = [9, 8 ,7];
8+
let newArrayWithoutSpread = [oldArray, 6, 5, 4, 3];
9+
let newArrayWithSpread = [...oldArray, 6, 5, 4, 3];
10+
11+
console.log("Without spread:");
12+
console.log(newArrayWithoutSpread);
13+
14+
console.log("With spread:");
15+
console.log(newArrayWithSpread);
16+
}
17+
18+
const spreadObject = () => {
19+
const originalPerson = {
20+
name: "Douglas",
21+
lastname: "Hernández"
22+
}
23+
24+
const newPersonWithoutSpread = {
25+
originalPerson,
26+
age: 22,
27+
gender: "Male"
28+
}
29+
30+
const newPersonWithSpread = {
31+
...originalPerson,
32+
age: 22,
33+
gender: "Male"
34+
}
35+
36+
console.log("Without spread:");
37+
console.log(newPersonWithoutSpread);
38+
39+
console.log("With spread:");
40+
console.log(newPersonWithSpread);
41+
42+
}
43+
44+
console.log("Arrays");
45+
spreadArray();
46+
47+
console.log("Objects");
48+
spreadObject();

6-Rest&Spread/Example2.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* Rest operator; It's used to declare that a functions is capable to receive n items of parameters, when we don't know
3+
* the exact value of n. This parameters are casted to an instance of Array
4+
*/
5+
6+
const sortNumbersAndList = (...numbers) => {
7+
numbers.sort();
8+
numbers.forEach((element, index) =>{
9+
console.log(`${index}: ${element}`);
10+
})
11+
}
12+
13+
sortNumbersAndList(1, 3, 5, 6, 7, 2, 4);

0 commit comments

Comments
 (0)