Tutorial by Examples

Pull properties from an object passed into a function. This pattern simulates named parameters instead of relying on argument position. let user = { name: 'Jill', age: 33, profession: 'Pilot' } function greeting ({name, profession}) { console.log(`Hello, ${name} the ${pr...
Destructuring allows us to refer to one key in an object, but declare it as a variable with a different name. The syntax looks like the key-value syntax for a normal JavaScript object. let user = { name: 'John Smith', id: 10, email: '[email protected]', }; let {user: userName, id: us...
const myArr = ['one', 'two', 'three'] const [ a, b, c ] = myArr // a = 'one', b = 'two, c = 'three' We can set default value in destructuring array, see the example of Default Value While Destructuring. With destructuring array, we can swap the values of 2 variables easily: var a = 1; var ...
Destructuring is a convenient way to extract properties from objects into variables. Basic syntax: let person = { name: 'Bob', age: 25 }; let { name, age } = person; // Is equivalent to let name = person.name; // 'Bob' let age = person.age; // 25 Destructuring and renaming: le...
Aside from destructuring objects into function arguments, you can use them inside variable declarations as follows: const person = { name: 'John Doe', age: 45, location: 'Paris, France', }; let { name, age, location } = person; console.log('I am ' + name + ', aged ' + age + ' and li...
If you ever need an array that consists of extra arguments that you may or may not expect to have, apart from the ones you specifically declared, you can use the array rest parameter inside the arguments declaration as follows: Example 1, optional arguments into an array: function printArgs(arg1, ...
We often encounter a situation where a property we're trying to extract doesn't exist in the object/array, resulting in a TypeError (while destructuring nested objects) or being set to undefined. While destructuring we can set a default value, which it will fallback to, in case of it not being found...
We are not limited to destructuring an object/array, we can destructure a nested object/array. Nested Object Destructuring var obj = { a: { c: 1, d: 3 }, b: 2 }; var { a: { c: x, d: y }, b: z } = obj; console.log(x, y, z); // 1,3,2 Nested Array ...

Page 1 of 1