Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an associative array as a variable name? - javascript

I was looking through some code from a firefox extension (here: https://github.com/mozilla/prospector/blob/master/oneLiner/bootstrap.js#L34 ) and I saw something I'd never seen before in javascript. The programmer has used an associative array as the variable name. Could someone explain to me how this variable referencing works?

const {classes: Cc, interfaces: Ci, utils: Cu} = Components;

I understand the "const" from reading this page: https://developer.mozilla.org/en/JavaScript/Reference/Statements/const

but how is it able to use an associative array object as a variable name?

Also, it seems to be using key names in the associative array as references to the Components methods (listed here: https://developer.mozilla.org/en/Components_object ). I always thought a key name had to go first and then the value, but this seems to put the value of the reference to the Components classes method first and then assign it to a name of Cc even though Cc is in the spot where a value would go (and Ci for the Components interfaces method & Cu for Components utils method).

like image 506
Yansky Avatar asked Apr 27 '12 12:04

Yansky


People also ask

Can we assign array to variable in JavaScript?

JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.

How do you write associative array in JavaScript?

An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.

What is the difference between [] and {} in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

What is the use of {} in JavaScript?

{} declares an object, with no members. Like an empty data container. [] would declare an empty array. Fun fact: Even arrays are objects in JavaScript.


1 Answers

What you are seeing is a Destructuring assignment, it is available since javascript 1.7 see this documentation for more information https://developer.mozilla.org/en/JavaScript/New_in_JavaScript/1.7

Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals. The object and array literal expressions provide an easy way to create ad-hoc packages of data. Once you've created these packages of data, you can use them any way you want to. You can even return them from functions.

like image 79
GillesC Avatar answered Oct 14 '22 01:10

GillesC