Sunday, May 12, 2024
116
rated 0 times [  117] [ 1]  / answers: 1 / hits: 30888  / 11 Years ago, fri, march 8, 2013, 12:00:00

Not sure if this is a Mozilla-specific JS syntax, but I often found variables being declared this way, for example, in add-on SDK docs:



var { Hotkey } = require(sdk/hotkeys);


and in various chrome Javascript (let statement is being used in place of var),



let { classes: Cc, interfaces: Ci, results: Cr, utils: Cu }  = Components;


I found it very confusing but I am not being able to find any documentation about both syntax, even on MDN.


More From » ecmascript-6

 Answers
7

They're both JavaScript 1.7 features. The first one is block-level variables:




let allows you to declare variables, limiting its scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.




The second one is called destructuring:




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

...

One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.




For those familiar with Python, it's similar to this syntax:



>>> a, (b, c) = (1, (2, 3))
>>> a, b, c
(1, 2, 3)


The first code chunk is shorthand for:



var {Hotkey: Hotkey} = require(sdk/hotkeys);
// Or
var Hotkey = require(sdk/hotkeys).Hotkey;


You can rewrite the second code chunk as:



let Cc = Components.classes;
let Ci = Components.interfaces;
let Cr = Components.results;
let Cu = Components.utils;

[#79738] Thursday, March 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shane

Total Points: 239
Total Questions: 91
Total Answers: 114

Location: Faroe Islands
Member since Tue, Jul 7, 2020
4 Years ago
shane questions
;