1

Does anyone know what this syntax means in JavaScript?

var { variable } = value;

I found it in some code examples and I've never seen this before. Is this JavaScript 6? I tried googling variable syntax and es6 but no examples came up with this syntax.

Here's the full example:

var { Tab } = require('app-dev-kit/tab');
var tab = Tab({ properties });

Weirdest part is if I drop parens from { Tab } then it doesn't work (it says Tab is not a function in that case):

var Tab = require('app-dev-kit/tab');
var tab = Tab({ properties });

This doesn't work: Error: Tab is not a function.

bodacydo
  • 75,521
  • 93
  • 229
  • 319
  • 5
    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – zerkms Nov 03 '15 at 00:14

1 Answers1

4

This is an ES6 feature known as destructuring assignment that works for arrays (array destructuring) and objects (object destructuring)

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

Say you have a function

function foo() {
    return { bar: 1, baz: 2 };
}

And you want to assign the properties of that functions returned value to local variables. Traditionally, you would do something like

var f = foo();
var bar = f.bar; 
var baz = f.baz;
console.log(bar); // 1
console.log(baz); // 2

With destructuring assignment, you can do this

var {bar, baz} = foo();
console.log(bar); // 1
console.log(baz); // 2
Griffith
  • 3,229
  • 1
  • 17
  • 30
  • Very confusing. This is something new. Any ideas what what does `require('app-dev-kit/tab')` does return in this case? And why is it designed this way? I'm used to regular `var thing = require('thing')`. – bodacydo Nov 03 '15 at 00:18
  • 1
    `console.log()` it and see. In that case it presumably returns an object with at least one property `Tab`. "And why is it designed this way?" --- ask the library developer. "I'm used to regular" - okay. – zerkms Nov 03 '15 at 00:19
  • It actually works with any object that is iterable, not just arrays. – Felix Kling Nov 03 '15 at 00:48