Search code examples
javascriptecmascript-6destructuring

Destructuring an object without specifying its properties


Is there an elegant solution to destructure an object without specifying all the object's properties?

I wondered if it was possible to use the spread operator but it seems like that's not possible because objects are not arrays!

I guess it may be considered a bad idea to blindly declare variables but I think this would be useful for very large objects.


Solution

  • This is what the with(){} construction allowed:

    var obj = {a: 1};
    with (obj) {
      console.log(a);
    }
    

    This construct is however severely discouraged and basically deprecated (it throws an error in strict mode), because it has some major drawbacks:

    • Your code is hard to read, because it's impossible to tell apart 1) Variables from outer scopes 2) Local variables 3) Properties coming from the object.

    • Your code can't be optimized, because the JavaScript engine can't tell where your variables are coming from.

    • Your code is much harder to refactor, because if you introduce a property to your obj, it might shadow some existing local variable, exemple:


    var obj = {};
    var a = 1;
    addSomeProperties(obj);
    with (obj) {
      console.log(a); // the result here depends on whether or not "addSomeProperties" puts a property named "a" on "obj"
    }
    

    TL;DR version: you really don't want this, it makes your code brittle, hard to read&refactor. Just pick the pieces you want apart using the "normal" destructuring syntax.