JavaScript - Data Structures, Modern Operators and Strings

Last Updated on: October 16, 2021 pm

JavaScript - Data Structures, Modern Operators and Strings

Destructuring Arrays

Switch the two variables.

1
[main, secondary] = [secondary, main]
1
2
const [p, q, r] = [8, 9];
console.log(p, q, r);

get r = undefined

Destructuring Objects

Set a default value

1
2
const { menu = [], starterMenu: starters = [] } = restaurant;
console.log(menu, starters);

Mutating Variables

1
2
3
4
5
let a = 111;
let b = 999;
const obj = { a: 23, b: 6, c: 234 };
({ a, b } = obj); // { } means code block
console.log(a, b);

{} means code block

Needs to wrap the destructuring assignment into parenthesis.

1
2
3
4
5
6
7
8
9
10
11
12
const restaurant = {
orderDelivery: function ({ starterIndex, mainIndex, time }) {
console.log(
`Order received! ${this.starterMenu[starterIndex]} will be delivered at ${time}`
);
},
}
restaurant.orderDelivery({
starterIndex: 1,
mainIndex: 1,
time: '22:40',
});

The Spread Operator

The spread operator ...arr takes all the elements from the array and it doesnt create new variables.

Only use it in places.

Copy Array

1
const mainMenuArray = [...restaurant.mainMenu]

Merge Arrays

1
const menu = [...restaurant.starterMenu, ...restaurant.mainMenu]

REST Pattern and Parameters

1
const [a, b, ...others] = [1, 2, 3, 5];

The rest patter always must be the last element in the array.