Skip to content

Instantly share code, notes, and snippets.

View gladchinda's full-sized avatar

Glad Chinda gladchinda

View GitHub Profile
const student = {
name: 'John Doe',
age: 16,
scores: {
maths: 74,
english: 63
}
};
// We define 3 local variables: name, maths, science
// This does no assignment
// Because of the empty nested object literal ({})
const { scores: {} } = student;
const rgb = [255, 200, 0];
// Array Destructuring
const [red, green, blue] = rgb;
console.log(`R: ${red}, G: ${green}, B: ${blue}`); // R: 255, G: 200, B: 0
const rgb = [200];
// Assign default values of 255 to red and blue
const [red = 255, green, blue = 255] = rgb;
console.log(`R: ${red}, G: ${green}, B: ${blue}`); // R: 200, G: undefined, B: 255
let red = 100;
let green = 200;
let blue = 50;
const rgb = [200, 255, 100];
// Destructuring assignment to red and green
[red, green] = rgb;
console.log(`R: ${red}, G: ${green}, B: ${blue}`); // R: 200, G: 255, B: 50
const rgb = [200, 255, 100];
// Skip the first two items
// Assign the only third item to the blue variable
const [,, blue] = rgb;
console.log(`Blue: ${blue}`); // Blue: 100
let width = 300;
let height = 400;
const landscape = true;
console.log(`${width} x ${height}`); // 300 x 400
if (landscape) {
// An extra variable needed to copy initial width
let initialWidth = width;
let width = 300;
let height = 400;
const landscape = true;
console.log(`${width} x ${height}`); // 300 x 400
if (landscape) {
// Swap the variables
[width, height] = [height, width];
const color = ['#FF00FF', [255, 0, 255], 'rgb(255, 0, 255)'];
// Use nested destructuring to assign red, green and blue
const [hex, [red, green, blue]] = color;
console.log(hex, red, green, blue); // #FF00FF 255 0 255
const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
// Assign the first and third items to red and yellow
// Assign the remaining items to otherColors variable using the spread operator(...)
const [red,, yellow, ...otherColors] = rainbow;
console.log(otherColors); // ['green', 'blue', 'indigo', 'violet']