undefined triggers default values...)Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment). How to extract the values is specified via patterns (read on for examples).
Destructuring objects:
constobj={first:'Jane',last:'Doe'};const{first:f,last:l}=obj;// f = 'Jane'; l = 'Doe'// {prop} is short for {prop: prop}const{first,last}=obj;// first = 'Jane'; last = 'Doe'
Destructuring helps with processing return values:
constobj={foo:123};const{writable,configurable}=Object.getOwnPropertyDescriptor(obj,'foo');console.log(writable,configurable);// true true
Array destructuring (works for all iterable values):
constiterable=['a','b'];const[x,y]=iterable;// x = 'a'; y = 'b'
Destructuring helps with processing return values:
const[all,year,month,day]=/^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec('2999-12-31');
Destructuring can be used in the following locations (I’m showing Array patterns to demonstrate; object patterns work just as well):
// Variable declarations:const[x]=['a'];let[x]=['a'];var[x]=['a'];// Assignments:[x]=['a'];// Parameter definitions:functionf([x]){···}f(['a']);
You can also destructure in afor-of loop:
constarr=['a','b'];for(const[index,element]ofarr.entries()){console.log(index,element);}// Output:// 0 a// 1 b
To fully understand what destructuring is, let’s first examine its broader context.
JavaScript has operations for constructing data, one property at a time:
constobj={};obj.first='Jane';obj.last='Doe';
The same syntax can be used to extract data. Again, one property at a time:
constf=obj.first;constl=obj.last;
Additionally, there is syntax to construct multiple properties at the same time, via anobject literal:
constobj={first:'Jane',last:'Doe'};
Before ES6, there was no corresponding mechanism for extracting data. That’s whatdestructuring is – it lets you extract multiple properties from an object via anobject pattern. For example, on the left-hand side of an assignment:
const{first:f,last:l}=obj;
You can also destructure Arrays via patterns:
const[x,y]=['a','b'];// x = 'a'; y = 'b'
The following two parties are involved in destructuring:
The destructuring target is either one of three patterns:
x{ first: «pattern», last: «pattern» }[ «pattern», «pattern» ]That means that you can nest patterns, arbitrarily deeply:
constobj={a:[{foo:123,bar:'abc'},{}],b:true};const{a:[{foo:f}]}=obj;// f = 123
If you destructure an object, you mention only those properties that you are interested in:
const{x:x}={x:7,y:3};// x = 7
If you destructure an Array, you can choose to only extract a prefix:
const[x,y]=['a','b','c'];// x='a'; y='b';
In an assignmentpattern = someValue, how does thepattern access what’s insidesomeValue?
The object pattern coerces destructuring sources to objects before accessing properties. That means that it works with primitive values:
const{length:len}='abc';// len = 3const{toString:s}=123;// s = Number.prototype.toString
The coercion to object is not performed viaObject(), but via the internal operationToObject(). The two operations handleundefined andnull differently.
Object() converts primitive values to wrapper objects and leaves objects untouched:
> typeof Object('abc')'object'> var obj = {};> Object(obj) === objtrueIt also convertsundefined andnull to empty objects:
> Object(undefined){}> Object(null){}In contrast,ToObject() throws aTypeError if it encountersundefined ornull. Therefore, the following destructurings fail, even before destructuring accesses any properties:
const{prop:x}=undefined;// TypeErrorconst{prop:y}=null;// TypeError
As a consequence, you can use the empty object pattern{} to check whether a value is coercible to an object. As we have seen, onlyundefined andnull aren’t:
({}=[true,false]);// OK, Arrays are coercible to objects({}='abc');// OK, strings are coercible to objects({}=undefined);// TypeError({}=null);// TypeError
The parentheses around the expressions are necessary because statements must not begin with curly braces in JavaScript (details are explained later).
Array destructuring uses an iterator to get to the elements of a source. Therefore, you can Array-destructure any value that is iterable. Let’s look at examples of iterable values.
Strings are iterable:
const[x,...y]='abc';// x='a'; y=['b', 'c']
Don’t forget that the iterator over strings returns code points (“Unicode characters”, 21 bits), not code units (“JavaScript characters”, 16 bits). (For more information on Unicode, consult the chapter “Chapter 24. Unicode and JavaScript” in “Speaking JavaScript”.) For example:
const[x,y,z]='a\uD83D\uDCA9c';// x='a'; y='\uD83D\uDCA9'; z='c'
You can’t access the elements of a Set via indices, but you can do so via an iterator. Therefore, Array destructuring works for Sets:
const[x,y]=newSet(['a','b']);// x='a'; y='b’;
TheSet iterator always returns elements in the order in which they were inserted, which is why the result of the previous destructuring is always the same.
A value is iterable if it has a method whose key isSymbol.iterator that returns an object. Array-destructuring throws aTypeError if the value to be destructured isn’t iterable:
letx;[x]=[true,false];// OK, Arrays are iterable[x]='abc';// OK, strings are iterable[x]={*[Symbol.iterator](){yield1}};// OK, iterable[x]={};// TypeError, empty objects are not iterable[x]=undefined;// TypeError, not iterable[x]=null;// TypeError, not iterable
TheTypeError is thrown even before accessing elements of the iterable, which means that you can use the empty Array pattern[] to check whether a value is iterable:
[]={};// TypeError, empty objects are not iterable[]=undefined;// TypeError, not iterable[]=null;// TypeError, not iterable
Default values are an optional feature of patterns. They provide a fallback if nothing is found in the source. If a part (an object property or an Array element) has no match in the source, it is matched against:
undefined (otherwise)Let’s look at an example. In the following destructuring, the element at index 0 has no match on the right-hand side. Therefore, destructuring continues by matchingx against 3, which leads tox being set to 3.
const[x=3,y]=[];// x = 3; y = undefined
You can also use default values in object patterns:
const{foo:x=3,bar:y}={};// x = 3; y = undefined
undefined triggers default valuesDefault values are also used if a part does have a match and that match isundefined:
const[x=1]=[undefined];// x = 1const{prop:y=2}={prop:undefined};// y = 2
The rationale for this behavior is explained in the next chapter, inthe section on parameter default values.
The default values themselves are only computed when they are needed. In other words, this destructuring:
const{prop:y=someFunc()}=someValue;
is equivalent to:
lety;if(someValue.prop===undefined){y=someFunc();}else{y=someValue.prop;}
You can observe that if you useconsole.log():
> function log(x) { console.log(x); return 'YES' }> const [a=log('hello')] = [];> a'YES'> const [b=log('hello')] = [123];> b123In the second destructuring, the default value is not triggered andlog() is not called.
A default value can refer to any variable, including other variables in the same pattern:
const[x=3,y=x]=[];// x=3; y=3const[x=3,y=x]=[7];// x=7; y=7const[x=3,y=x]=[7,2];// x=7; y=2
However, order matters: the variablesx andy are declared from left to right and produce aReferenceError if they are accessed before their declarations:
const[x=y,y=3]=[];// ReferenceError
So far we have only seen default values for variables, but you can also associate them with patterns:
const[{prop:x}={}]=[];
What does this mean? Recall the rule for default values: If a part has no match in the source, destructuring continues with the default value.
The element at index 0 has no match, which is why destructuring continues with:
const{prop:x}={};// x = undefined
You can more easily see why things work this way if you replace the pattern{ prop: x } with the variablepattern:
const[pattern={}]=[];
Let’s further explore default values for patterns. In the following example, we assign a value tox via the default value{ prop: 123 }:
const[{prop:x}={prop:123}]=[];
Because the Array element at index 0 has no match on the right-hand side, destructuring continues as follows andx is set to 123.
const{prop:x}={prop:123};// x = 123
However,x is not assigned a value in this manner if the right-hand side has an element at index 0, because then the default value isn’t triggered.
const[{prop:x}={prop:123}]=[{}];
In this case, destructuring continues with:
const{prop:x}={};// x = undefined
Thus, if you wantx to be 123 if either the object or the property is missing, you need to specify a default value forx itself:
const[{prop:x=123}={}]=[{}];
Here, destructuring continues as follows, independently of whether the right-hand side is[{}] or[].
const{prop:x=123}={};// x = 123
Alater section explains destructuring from a different angle, as an algorithm. That may give you additional insight.
Property value shorthands are a feature of object literals: If the property value is a variable that has the same name as the property key then you can omit the key. This works for destructuring, too:
const{x,y}={x:11,y:8};// x = 11; y = 8// Same as:const{x:x,y:y}={x:11,y:8};
You can also combine property value shorthands with default values:
const{x,y=1}={};// x = undefined; y = 1
Computed property keys are another object literal feature that also works for destructuring. You can specify the key of a property via an expression, if you put it in square brackets:
constFOO='foo';const{[FOO]:f}={foo:123};// f = 123
Computed property keys allow you to destructure properties whose keys are symbols:
// Create and destructure a property whose key is a symbolconstKEY=Symbol();constobj={[KEY]:'abc'};const{[KEY]:x}=obj;// x = 'abc'// Extract Array.prototype[Symbol.iterator]const{[Symbol.iterator]:func}=[];console.log(typeoffunc);// function
Elision lets you use the syntax of Array “holes” to skip elements during destructuring:
const[,,x,y]=['a','b','c','d'];// x = 'c'; y = 'd'
...)Therest operator lets you extract the remaining elements of an iterable into an Array. If this operator is used inside an Array pattern, it must come last:
const[x,...y]=['a','b','c'];// x='a'; y=['b', 'c']
The spread operator has exactly the same syntax as the rest operator – three dots. But they are different: the former contributes data to Array literals and function calls, whereas the latter is used for destructuring and extracts data.
If the operator can’t find any elements, it matches its operand against the empty Array. That is, it never producesundefined ornull. For example:
const[x,y,...z]=['a'];// x='a'; y=undefined; z=[]
The operand of the rest operator doesn’t have to be a variable, you can use patterns, too:
const[x,...[y,z]]=['a','b','c'];// x = 'a'; y = 'b'; z = 'c'
The rest operator triggers the following destructuring:
[y,z]=['b','c']
If you assign via destructuring, each assignment target can be everything that is allowed on the left-hand side of a normal assignment.
For example, a reference to a property (obj.prop):
constobj={};({foo:obj.prop}={foo:123});console.log(obj);// {prop:123}
Or a reference to an Array element (arr[0]):
constarr=[];({bar:arr[0]}={bar:true});console.log(arr);// [true]
You can also assign to object properties and Array elements via the rest operator (...):
constobj={};[first,...obj.prop]=['a','b','c'];// first = 'a'; obj.prop = ['b', 'c']
If youdeclare variables or define parameters via destructuring then you must use simple identifiers, you can’t refer to object properties and Array elements.
There are two things to be mindful of when using destructuring:
The next two sections contain the details.
Because code blocks begin with a curly brace, statements must not begin with one. This is unfortunate when using object destructuring in an assignment:
{a,b}=someObject;// SyntaxError
The work-around is to put the complete expression in parentheses:
({a,b}=someObject);// OK
The following syntax does not work:
({a,b})=someObject;// SyntaxError
Withlet,var andconst, curly braces never cause problems:
const{a,b}=someObject;// OK
Let’s start with a few smaller examples.
Thefor-of loop supports destructuring:
constmap=newMap().set(false,'no').set(true,'yes');for(const[key,value]ofmap){console.log(key+' is '+value);}
You can use destructuring to swap values. That is something that engines could optimize, so that no Array would be created.
[a,b]=[b,a];
You can use destructuring to split an Array:
const[first,...rest]=['a','b','c'];// first = 'a'; rest = ['b', 'c']
Some built-in JavaScript operations return Arrays. Destructuring helps with processing them:
const[all,year,month,day]=/^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec('2999-12-31');
If you are only interested in the groups (and not in the complete match,all), you can use elision to skip the array element at index 0:
const[,year,month,day]=/^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec('2999-12-31');
exec() returnsnull if the regular expression doesn’t match. Unfortunately, you can’t handlenull via default values, which is why you must use the Or operator (||) in this case:
const[,year,month,day]=/^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec(someStr)||[];
Array.prototype.split() returns an Array. Therefore, destructuring is useful if you are interested in the elements, not the Array:
constcells='Jane\tDoe\tCTO'const[firstName,lastName,title]=cells.split('\t');console.log(firstName,lastName,title);
Destructuring is also useful for extracting data from objects that are returned by functions or methods. For example, the iterator methodnext() returns an object with two properties,done andvalue. The following code logs all elements of Arrayarr via the iteratoriter. Destructuring is used in line A.
constarr=['a','b'];constiter=arr[Symbol.iterator]();while(true){const{done,value}=iter.next();// (A)if(done)break;console.log(value);}
Array-destructuring works with any iterable value. That is occasionally useful:
const[x,y]=newSet().add('a').add('b');// x = 'a'; y = 'b'const[a,b]='foo';// a = 'f'; b = 'o'
To see the usefulness of multiple return values, let’s implement a functionfindElement(a, p) that searches for the first element in the Arraya for which the functionp returnstrue. The question is: what shouldfindElement() return? Sometimes one is interested in the element itself, sometimes in its index, sometimes in both. The following implementation returns both.
functionfindElement(array,predicate){for(const[index,element]ofarray.entries()){// (A)if(predicate(element,index,array)){// We found an element:return{element,index};// Same as (property value shorthands):// { element: element, index: index }}}// We couldn’t find anything; return failure values:return{element:undefined,index:-1};}
The function iterates over all elements ofarray, via the Array methodentries(), which returns an iterable over[index,element] pairs (line A). The parts of the pairs are accessed via destructuring.
Let’s usefindElement():
constarr=[7,8,6];const{element,index}=findElement(arr,x=>x%2===0);// element = 8, index = 1
Several ECMAScript 6 features allowed us to write more concise code: The callback is an arrow function; the return value is destructured via an object pattern with property value shorthands.
Due toindex andelement also referring to property keys, the order in which we mention them doesn’t matter. We can swap them and nothing changes:
const{index,element}=findElement(···);
We have successfully handled the case of needing both index and element. What if we are only interested in one of them? It turns out that, thanks to ECMAScript 6, our implementation can take care of that, too. And the syntactic overhead compared to functions with single return values is minimal.
consta=[7,8,6];const{element}=findElement(a,x=>x%2===0);// element = 8const{index}=findElement(a,x=>x%2===0);// index = 1
Each time, we only extract the value of the one property that we need.
This section looks at destructuring from a different angle: as a recursive pattern matching algorithm.
This different angle should especially help with understanding default values. If you feel you don’t fully understand them yet, read on.
At the end, I’ll use the algorithm to explain the difference between the following two function declarations.
functionmove({x=0,y=0}={}){···}functionmove({x,y}={x:0,y:0}){···}
A destructuring assignment looks like this:
«pattern»=«value»
We want to usepattern to extract data fromvalue. I’ll now describe an algorithm for doing so, which is known in functional programming aspattern matching (short:matching). The algorithm specifies the operator← (“match against”) for destructuring assignment that matches apattern against avalue and assigns to variables while doing so:
«pattern»←«value»
The algorithm is specified via recursive rules that take apart both operands of the← operator. The declarative notation may take some getting used to, but it makes the specification of the algorithm more concise. Each rule has two parts:
Let’s look at an example:
{key: «pattern», «properties»} ← obj«pattern»←obj.key{«properties»}←obj
{} ← obj (no properties left)// Nothing to do
In rule (2c), the head means that this rule is executed if there is an object pattern with at least one property and zero or more remaining properties. That pattern is matched against a valueobj. The effect of this rule is that execution continues with the property value pattern being matched againstobj.key and the remaining properties being matched againstobj.
In rule (2e), the head means that this rule is executed if the empty object pattern{} is matched against a valueobj. Then there is nothing to be done.
Whenever the algorithm is invoked, the rules are checked top to bottom and only the first rule that is applicable is executed.
I only show the algorithm for destructuring assignment. Destructuring variable declarations and destructuring parameter definitions work similarly.
I don’t cover advanced features (computed property keys; property value shorthands; object properties and array elements as assignment targets), either. Only the basics.
A pattern is either:
x{«properties»}[«elements»]Each of the following sections describes one of these three cases.
The following three sections specify how to handle these three cases. Each section contains one or more numbered rules.
x ← value (includingundefined andnull)x=value
{«properties»} ← undefinedthrownewTypeError();
{«properties»} ← nullthrownewTypeError();
{key: «pattern», «properties»} ← obj«pattern»←obj.key{«properties»}←obj
{key: «pattern» = default_value, «properties»} ← objconsttmp=obj.key;if(tmp!==undefined){«pattern»←tmp}else{«pattern»←default_value}{«properties»}←obj
{} ← obj (no properties left)// Nothing to do
Array pattern and iterable. The algorithm for Array destructuring starts with an Array pattern and an iterable:
[«elements»] ← non_iterableassert(!isIterable(non_iterable))thrownewTypeError();
[«elements»] ← iterableassert(isIterable(iterable))constiterator=iterable[Symbol.iterator]();«elements»←iterator
Helper function:
functionisIterable(value){return(value!==null&&typeofvalue==='object'&&typeofvalue[Symbol.iterator]==='function');}
Array elements and iterator. The algorithm continues with the elements of the pattern (left-hand side of the arrow) and the iterator that was obtained from the iterable (right-hand side of the arrow).
«pattern», «elements» ← iterator«pattern»←getNext(iterator)// undefined after last item«elements»←iterator
«pattern» = default_value, «elements» ← iteratorconsttmp=getNext(iterator);// undefined after last itemif(tmp!==undefined){«pattern»←tmp}else{«pattern»←default_value}«elements»←iterator
, «elements» ← iterator (hole, elision)getNext(iterator);// skip«elements»←iterator
...«pattern» ← iterator (always last part!)consttmp=[];for(constelemofiterator){tmp.push(elem);}«pattern»←tmp
← iterator (no elements left)// Nothing to do
Helper function:
functiongetNext(iterator){const{done,value}=iterator.next();return(done?undefined:value);}
In ECMAScript 6, you can simulate named parameters if the caller uses an object literal and the callee uses destructuring. This simulation is explained in detail inthe chapter on parameter handling. The following code shows an example: functionmove1() has two named parameters,x andy:
functionmove1({x=0,y=0}={}){// (A)return[x,y];}move1({x:3,y:8});// [3, 8]move1({x:3});// [3, 0]move1({});// [0, 0]move1();// [0, 0]
There are three default values in line A:
x andy.move1() without parameters (as in the last line).But why would you define the parameters as in the previous code snippet? Why not as follows – which is also completely legal ES6 code?
functionmove2({x,y}={x:0,y:0}){return[x,y];}
To see whymove1() is correct, let’s use both functions for two examples. Before we do that, let’s see how the passing of parameters can be explained via matching.
For function calls, formal parameters (inside function definitions) are matched against actual parameters (inside function calls). As an example, take the following function definition and the following function call.
functionfunc(a=0,b=0){···}func(1,2);
The parametersa andb are set up similarly to the following destructuring.
[a=0,b=0]←[1,2]
move2()Let’s examine how destructuring works formove2().
Example 1.move2() leads to this destructuring:
[{x,y}={x:0,y:0}]←[]
The single Array element on the left-hand side does not have a match on the right-hand side, which is why{x,y} is matched against the default value and not against data from the right-hand side (rules 3b, 3d):
{x,y}←{x:0,y:0}
The left-hand side containsproperty value shorthands, it is an abbreviation for:
{x:x,y:y}←{x:0,y:0}
This destructuring leads to the following two assignments (rules 2c, 1):
x=0;y=0;
Example 2. Let’s examine the function callmove2({z:3}) which leads to the following destructuring:
[{x,y}={x:0,y:0}]←[{z:3}]
There is an Array element at index 0 on the right-hand side. Therefore, the default value is ignored and the next step is (rule 3d):
{x,y}←{z:3}
That leads to bothx andy being set toundefined, which is not what we want.
move1()Let’s trymove1().
Example 1:move1()
[{x=0,y=0}={}]←[]
We don’t have an Array element at index 0 on the right-hand side and use the default value (rule 3d):
{x=0,y=0}←{}
The left-hand side contains property value shorthands, which means that this destructuring is equivalent to:
{x:x=0,y:y=0}←{}
Neither propertyx nor propertyy have a match on the right-hand side. Therefore, the default values are used and the following destructurings are performed next (rule 2d):
x←0y←0
That leads to the following assignments (rule 1):
x=0y=0
Example 2:move1({z:3})
[{x=0,y=0}={}]←[{z:3}]
The first element of the Array pattern has a match on the right-hand side and that match is used to continue destructuring (rule 3d):
{x=0,y=0}←{z:3}
Like in example 1, there are no propertiesx andy on the right-hand side and the default values are used:
x=0y=0
The examples demonstrate that default values are a feature of pattern parts (object properties or Array elements). If a part has no match or is matched againstundefined then the default value is used. That is, the pattern is matched against the default value, instead.