Answers for "array destructuring"

3

destructuring arrays with rest operator

// Rest operator on Arrays;
// It's usually shown as ...rest
// but you can name this what you like
// Think of it as "get the ...rest of the array"
const [q, r, ...callThisAnythingYouWant] = [1, 2, 3, 4, 5, 6, 7, 8];

console.log(q, r); // 1 2
console.log(callThisAnythingYouWant); // [ 3, 4, 5, 6, 7, 8 ]
Posted by: Guest on March-05-2020
39

javascript object destructuring

//simple example with object------------------------------
let obj = {name: 'Max', age: 22, address: 'Delhi'};
const {name, age} = obj;

console.log(name);
//expected output: "Max"

console.log(age);
//expected output: 22

console.log(address);
//expected output: Uncaught ReferenceError: address is not defined

// simple example with array-------------------------------
let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: Array [30,40,50]
Posted by: Guest on May-16-2020
8

object destructuring

const book = {
    title: 'Ego is the Enemy',
    author: 'Ryan Holiday',
    publisher: {
        name: 'Penguin',
        type: 'private'
    }
};

const {title: bookName =  'Ego', author, name: {publisher: { name }} = book, type: {publisher: { type }} = book } = book;
Posted by: Guest on March-18-2020
3

Destructuring Assignment

const HIGH_TEMPERATURES = {
  yesterday: 75,
  today: 77,
  tomorrow: 80
};

//ES6 assignment syntax
const {today, tomorrow} = HIGH_TEMPERATURES;

//ES5 assignment syntax
const today = HIGH_TEMPERATURES.today;
const tomorrow = HIGH_TEMPERATURES.tomorrow;

console.log(today); // 77
console.log(tomorrow); // 80
console.log(yesterday); // "ReferenceError: yesterday is not defined" as it should be.
Posted by: Guest on January-07-2021
5

array destructuring

//Without destructuring

const myArray = ["a", "b", "c"];

const x = myArray[0];
const y = myArray[1];

console.log(x, y); // "a" "b"

//With destructuring

const myArray = ["a", "b", "c"];

const [x, y] = myArray; // That's it !

console.log(x, y); // "a" "b"
Posted by: Guest on January-18-2021
0

Array Destructuring

const foo = ['one', 'two', 'three'];

const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
Posted by: Guest on July-25-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language