How do I destructure all properties into the current scope/closure in ES2015?
I think you're looking for the with
statement, it does exactly what you are asking for:
const vegetableColors = {corn: 'yellow', peas: 'green'};
with (vegetableColors) {
console.log(corn);// yellow
console.log(peas);// green
}
However, it is deprecated (in strict mode, which includes ES6 modules), for good reason.
destructure all properties into the current scope
You cannot in ES61. And that's a good thing. Be explicit about the variables you're introducing:
const {corn, peas} = vegetableColors;
Alternatively, you can extend the global object with Object.assign(global, vegetableColors)
to put them in the global scope, but really, that's worse than a with
statement.
1: … and while I don't know whether there is a draft to allow such things in ES7, I can tell you that any proposal will be nuked by the TC :-)
ES2015 Destructure object twice in same scope
You can wrap the assignment in parens to reassign the variables via destructuring. The reason this is necessary is because otherwise the {
is assumed by the parser to begin a block rather than an object literal or assignment pattern. This blog post explains the situation in more detail.
function(oldState, newState) {
let {foo, bar} = oldState;
// do stuff //
({foo, bar} = newState);
}
How to destructure into dynamically named variables in ES6?
Short answer: it's impossible and it won't be possible.
Reasoning behind this: it would introduce new dynamically named variables into block scope, effectively being dynamic eval
, thus disabling any performance optimization. Dynamic eval
that can modify scope in fly was always regarded as extremely dangerous and was removed from ES5 strict mode.
Moreover, it would be a code smell - referencing undefined variables throws ReferenceError
, so you would need more boilerplate code to safely handle such dynamic scope.
Related Topics
Where's the Connection Between Index.HTML and Index.Js in a Create-React-App Application
Pass a JavaScript Variable Value into Input Type Hidden Value
How to Make a Radio Button Unchecked by Clicking It
How to Add "Href" Attribute to a Link Dynamically Using JavaScript
What Is a Text Node, Its Uses? //Document.Createtextnode()
How to Save Canvas Animation as Gif or Webm
HTML Mobile -Forcing the Soft Keyboard to Hide
When Loading an HTML Page via Ajax, Will Script Tags Be Loaded
How to Resize HTML Canvas Element
How to Retain the Scroll Position of a Scrollable Area When Pressing Back Button
Making Sure at Least One Checkbox Is Checked
How to Detect CSS Flex Wrap Event
Change Image Based on Dropdown Using JavaScript
Detect Double Tap on iPad or iPhone Screen Using JavaScript
Cross-Browser Window Resize Event - JavaScript/Jquery