I'm learning about destructuring and had a quick query on how to refer to the elements of an array.
I'm destructuring a nested array within an object in a function's parameter using:
function ajaxOptions({
url,
headers: [
header0 ="Content-Type: text/plain",
...otherHeaders
] = [],
data
} = {}) {
//... function body
}
which is giving a default value to the first element, header0
and spreading the other array elements.
But if I had a settings object:
var settings = {
url: 'http://someothersite.com',
data: 50,
callback: sayHello,
headers: [, 'Header2', 'Header3']
}
and passed it to ajaxOptions(settings)
I can't use header0
in the settings object to refer to the array element that's destructured in ajaxOptions can I? In other words I can't use it as a named argument like 'url', 'data' and 'callback' kind of are?
Hope that makes sense. Here's the complete code if it helps:
function ajaxOptions({
url: url = "http://www.example.com",
method: method = "post",
headers: [
header0 ="Content-Type: text/plain",
...otherHeaders
] = [],
data: data,
callback: callback
} = {}) {
return { url, method, headers: [header0, ...otherHeaders], data, callback};
}
function sayHello(){
console.log('hello');
}
var defaults = ajaxOptions();
var settings = {
url: 'http://someothersite.com',
data: 50,
callback: sayHello,
headers: [, header0 = 'New Header', 'Header2', 'Header3']
}
console.log(ajaxOptions(settings));
Thanks
header0
in your parameter list is a parameter, a local variable, just like a
is a parameter in:
function test(a) { }
And just like you cannot reference a
by name outside of that test
function, neither can you do that with your code and header0
. So if you call your function with header0 =
, you are actually defining a global variable header0
and assigning it a value on the spot. It would produce an error in strict mode. It has nothing to do with the parameter header0
.
The parameter header0
will get its value from the first element of the array you pass as headers
property value. If the object you pass as argument does not have the headers
property, or that property does not define a first array element that is different from undefined
, then the local headers0
variable will get the default value.
This variable is not to be confused with the property name followed by a colon, that also appears in your parameter section: headers:
. This is not a variable, but is merely defining the spot from where variables headers0
and otherHeaders
should get their values when the function is called. But headers
itself is not a variable.
url
on the other hand is a variable. It takes its value from the property with the same name. Notice the lack of the colon. That makes it a variable (parameter).
The syntax used in destructuring can be quite confusing. For instance, if instead of url,
you would have url: url2
, then instead of defining variable url
, you define variable url2
-- still being the value that the url
property has in the object that you pass to the function.