Skip to content Skip to sidebar Skip to footer

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 tha

Solution 1:

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.

Post a Comment for "Destructuring An Object Without Specifying Its Properties"