ES6 provides a new way to extract values from an array or object. Let's see some examples of destructuring -
Destructuring Assignment of Array -
- Destructuring all values
let arr = [1, 2, 3]; let [x, y, z] = arr; console.log(x, y, z); Output - 1 2 3
- Destructuring all partial values
let arr = [1, 2, 3]; let [x, y] = arr; console.log(x, y); Output - 1 2
- Skipping values
let arr = [1, 2, 3]; let [x,, z] = arr; console.log(x, z); Output - 1 3
- Destructuring default value
let arr = [1, 2, 3]; let [x, y, z, a] = arr; console.log(x, y, z, a); Output - 1 2 3 undefined
- Destructuring rest values of the array
let arr = [1, 2, 3]; let [x, ...rest] = arr; console.log(x, rest); Output - 1 Array [2, 3]
- Swap number using destructuring
let a = 1, b = 3; [a, b] = [b, a]; console.log(a, b) Output - 3 1
Destructuring Assignment of Object -
const emp = { id: 1, fName: 'Arun', lName: 'Taneja' }; const {fName, lName} = emp; console.log(fName, lName); Output - "Arun" "Taneja"
No comments:
Post a Comment