Hi I was going through examples of object destructuring use in passing function parameters here Object Destructuring Demo
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = **{}**) {
console.log(size, cords, radius);
// do some chart drawing
}
// In Firefox, default values for destructuring assignments are not yet
implemented (as described below).
// The workaround is to write the parameters in the following way:
// ({size: size = 'big', cords: cords = { x: 0, y: 0 }, radius: radius =
25} = **{}**)
drawES6Chart({
cords: { x: 18, y: 30 },
radius: 30
});
Can anybody let me know what is reason of using empty object assignment at the end of function parameter which I have marked in bold(embedded in double stars) above?
If you use it, and call the function with no parameters, it works:
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES6Chart();
if not, an error is thrown:
TypeError: can't convert undefined to object
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES6Chart();
The destructuring with defaults only does its thing when you pass an object which doesn't have the respective properties. The = {} default for the whole parameter allows to not pass an (empty) object at all.
It makes drawES6Chart() equivalent to drawES6Chart({}).
You have an object with your default values, but that object is an argument too, so it needs an empty object as a default value for the first argument, which is the object with the filled in values.
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
}
That, in pseudo code, would be:
function drawES6Chart({**first argument**} = {**default value for first argument**}) {
}
Here is a (much longer than I originally intended) description of the phenomenon
you are observing from a more rigorous point of view. Why more rigorous? I
wanted to investigate this question because I wasn't sure if there was some
special rule regarding function default arguments, or if there was something
fundamental about destructuring that I didn't understand. Turns out, it was the
latter.
I'll describe my findings using pseudo-grammar that somewhat mirrors what you'll
see in ECMA-262. That is my only reference.
Key Points:
There are the Destructuring Assignments and Destructuring Binding
Patterns. The purpose of both is to introduce names and assign
values.
Destructuring Assignment:
ObjectAssignmentPattern : '{' AssignmentPropertyList '}' = AssignmentExpression
AssignmentPropertyList : AssignmentProperty [',' AssignmentProperty]
These two just state the general form of the Destructuring Assignment.
AssignmentProperty : IdentifierReference [Initializer]
This is a "default value" for a name in the LHS.
AssignmentProperty : PropertyName ':' AssignmentElement
AssignmentElement : LeftHandSideExpression [Initializer]
This lets the destructuring nest recursively, but the semantics need to be
defined.
Semantics
If you look at
DestructuringAssignmentEvaluation,
you can see who gets assigned to what. ObjectAssignmentPattern is not very
interesting, it gives the basic '{' assignments '}' structure of the LHS,
what's more interesting is 12.15.5.3,
PropertyDestructuringAssignmentEvaluation. This shows what happens when you
actually assign default values, and when you bind more deeply nested names.
AssignmentProperty : IdentifierReference [Initializer]
Step 3 is important in this algorithm, where GetV is called. In this call, it
is attempting to get the value of the name that is currently being assigned to
(LHS) from value (RHS). This can throw, and is why the following snippet
throws:
y = Object.defineProperty({},'foo',{get: () => {throw new Error("get foo");}})
{foo} = y;
The next step, step 4, just evaluates the initializer if it exists and the
value obtained from the RHS is undefined. For example:
y = Object.defineProperty({},'foo',{get: () => undefined})
{foo = 3} = y; // foo === 3
Note that this step, and the step of actually "putting" the value where it needs
to go, can both throw. The next item is more tricky, and is where confusion
most certainly arises:
AssignmentProperty : PropertyName ':' AssignmentElement
The semantics here are to kick the can down the road to
KeyedDestructuringAssignmentEvaluation,
passing the PropertyName and current value (RHS). Here's the header for its
runtime semantics:
AssignmentElement : DestructuringAssignmentTarget [Initializer]
The steps of the ensuing algorithm are somewhat familiar, with a few surprises
and indirections. Almost any step in this algorithm can throw, so it won't be
pointed out explicitly. Step 1 is another "base of recursion," saying that if
the target is not an object or array literal (e.g. just an identifier), then let
lref be that (note that it doesn't have to be an identifier, just something
that can be assigned to, e.g.
w = {}
{x:w.u = 7} = {x:3} // w == {u:3}
Then, an attempt to retrieve the "target value" value.propertyName is made,
using GetV. If this value is undefined, an attempt is made to get the
intializer value, which in step 6 is put into lref. Step 5 is the recursive
call, peeling off as many layers as necessary to achieve the base case for the
destructured assignment. Here are a few more examples that I think illustrate
the point.
More clarifying Examples:
{x={y:1}} = {} // x == {y:1}
{x:{y=1}} = {} // error, {}.x is undefined, tried to find {}.x.y
x = 'foo'
{x:{y=1}} = {x} // x == 'foo', y == 1.
// x doesn't get assigned in this destructuring assignment,
// RHS becomes {x:x} === {x:'foo'} and since 'foo'.y is
// undefined, y gets the default 1
{x:{y=1}} = {x:{y}} // error, tried to give object value {y} === {y:y} to x
// in RHS, but y is undefined at that point
y = 'foo'
{x:{y=1}} = {x:{y}} // y == 'foo', gave {y} === {y:y} === {y:'foo'} to x in RHS
{x:{y=1}} = {x:{y:2}} // y == 2, maybe what you wanted?
// exercises:
{x=1} = undefined // error
{x=1} = null // error
{x=1} = null || undefined // error
{x=1} = null | undefined // can you guess? x == 1
Function Declarations
I actually started looking into destructuring after seeing the following code in
the source for react-redux:
export function createConnect({
connectHOC = connectAdvanced,
mapStateToPropsFactories = defaultMapStateToPropsFactories,
mapDispatchToPropsFactories = defaultMapDispatchToPropsFactories,
mergePropsFactories = defaultMergePropsFactories,
selectorFactory = defaultSelectorFactory
} = {}) {
So, the first place I started digging was:
14.1 Function Definitions
Here is a little "stack trace" trying to track down the relevant productions to
get me to the binding stuff.
FunctionDeclaration
FormalParameters
FormalParameterList
FormalParameter
-> 13.3.3 Destructuring Binding Patterns
BindingElement
+SingleNameBinding
++BindingIdentifier, Initializer
+BindingPattern
+ObjectBindingPattern
+BindingPropertyList
+BindingProperty
+SingleNameBinding,
+PropertyName ':' BindingElement
Semantics: Destructuring Binding vs. Destructuring Assignment
As far as I can tell, the only difference between Destructuring Binding and
Destructuring Assignment is where they can be used and how different lexical
environments are handled. Destructuring Binding outside of formal parameter
lists (and the like) require initializers, and Destructuring Binding is passed
an environment explicitly, while assignments, which by their definition implie
an initializer," get their values from the "ambience." I'd be very happy to hear
why that's wrong, but here is a quick demonstration:
var {x}; // syntax error
function noInit({x}) { return x; }
// ok
noInit() // runtime error
noInit({}) // undefined
noInit({x:4}) // 4
function binding({x:y} = {x:y}){ return y; }
function assigning(){({x:y} = {x:y}); return y}
binding() // error, cannot access y before initialization
assigning() // error, y is not defined
y = 0
binding() // still error
assigning() // 0 - now y is defined
Conclusion:
I conclude the following. The purpose of destructuring binding and assignment
is to introduce names into the current lexical environment, optionally assigning
them values. Nested destructuring is to carve out the shape of the data you
want, and you don't get the names above you for free. You can have initializers
as default values, but as soon as you use them you can't carve any deeper. If
you carve out a particular shape (a tree, in fact), what you attempt to bind to
may have undefined leaves, but the branch nodes must match what you've
described (name and shape).
Addendum
When I started this I found it helpful and interesting to see what tsc (the typescript compiler) would transpile these things into, given a target that does not support destructuring.
The following code:
function f({A,B:{BB1=7,BB2:{BBB=0}}}) {}
var z = 0;
var {x:{y=8},z} = {x:{},z};
Transpiles (tsc --target es5 --noImplicitAny false) into:
function f(_a) {
var A = _a.A,
_b = _a.B,
_c = _b.BB1,
BB1 = _c === void 0 ? 7 : _c,
_d = _b.BB2.BBB,
BBB = _d === void 0 ? 0 : _d;
}
var z = 0;
var _a = { x: {}, z: z },
_b = _a.x.y,
y = _b === void 0 ? 8 : _b,
z = _a.z;
That's a default value for the function parameter. Without using = {} JavaScript interpreter throws an error when there is no object passed to the function as it can't destructure an undefined value.
Related
I was wondering about how typescript would compile an enumeration into a javascript code. So I implemented the following example:
enum Contagens {
UM,
DOIS,
TRES
}
And it was compiled into this:
"use strict";
var Contagens;
(function (Contagens) {
Contagens[Contagens["UM"] = 0] = "UM";
Contagens[Contagens["DOIS"] = 1] = "DOIS";
Contagens[Contagens["TRES"] = 2] = "TRES";
})(Contagens || (Contagens = {}));
But, I don't understand how it works... someone could explain this code to me?
The variable var Contagens; This creates the variable that will hold a reference to the enum.
The argument Contagens || (Contagens = {}) the enum is used if it already exists, and will be set to an empty object, if it doesn't. This allows enums to be extended:
enum Contagens {
UM,
DOIS,
TRES
}
enum Contagens {
CATRE = 4
}
The function function (Contagens) { takes an argument Contagens that is the value from step #2. In this function it will create the entries on the enum object. It has the same name as the outer variable Contagens, so it shadows that variable. But it's the same value, so that doesn't matter much.
The assignment.
Contagens[Contagens["UM"] = 0] = "UM";
The result of an assignment is the value being assigned.* So Contagens["UM"] = 0 does two things. It sets the key "UM" to the value 0, and it returns 0.
That returned 0 is used then in the a second assignment:
Contagens[0] = "UM";
Now the "UM" property has been assigned 0 and the 0 property has been assigned to "UM". The enum now looks like this:
{ UM: 0, "0": "UM" }
This allows you to lookup a value in an enum by its name, or get its name from its value.
Contagens.UM // 0
Contagens[0] // "UM"
Which is handy!
* The result of an assignment when delcaring a variable is undefined, but assigning a property of an object or assigning to an existing variable will return the assigned value. JS is quirky like that.
For example, I have the following JS object:
var obj = {
n: 0,
o: {}
};
var nGlobal = obj.n;
var oGlobal = obj.o;
And want to use global variables in order to make it look like this:
var obj = {
n: 5,
o: {
x: 7
}
};
Obviously, I am able to assign a value to a property of oGlobal:
oGlobal.x = 7;
However, is there any way to change the value of obj.n through nGlobal, without mentioning obj?
Just something like this:
console.log(obj); // {n: 1, o: {}}
nGlobal.set(5);
// or
nGlobal.value = 5;
console.log(obj); // {n: 5, o: {}}
Short answer:
No, there is not.
Long answer:
In JS primitive types are immutable and passed by values.
JS implements pass-by-value strategy, which means that ALL data is always passed by value (in case if you pass a reference to object - the reference is passed by value)
One important consequence from the items above: in JS there is no way to change the original object using the = operation. That is: you can modify an object when you have a reference to it, but you cannot swap one object with something else so that all other references also "were modified".
Related:
Evaluation strategy - Call by sharing
Credits:
Felix Kling
The following TypeScript:
enum PrimaryColors { Red, Green, Blue };
Produces the following JavaScript:
var PrimaryColors;
(function (PrimaryColors) {
PrimaryColors[PrimaryColors["Red"] = 0] = "Red";
PrimaryColors[PrimaryColors["Green"] = 1] = "Green";
PrimaryColors[PrimaryColors["Blue"] = 2] = "Blue";
})(PrimaryColors || (PrimaryColors = {}));
;
I am embarrassed to admit that I don't understand what the JavaScript is doing.
The function in parentheses is assigning string values using another assignment as the index/key. I have not seen anything like this before.
And what is the purpose of the (PrimaryColors || (PrimaryColors = {}) following the function?
If the answer is to learn JavaScript properly, I will readily accept it, provided it comes with a suggested source that clearly explains what I am seeing here.
I believe:
PrimaryColors[PrimaryColors["Red"] = 0] = "Red";
is equivalent to:
PrimaryColors[0] = "Red";
PrimaryColors["Red"] = 0;
See this reference.
The expression x = 7 is an example of the first type. This expression
uses the = operator to assign the value seven to the variable x. The
expression itself evaluates to seven.
For example:
console.log((x = 7));
outputs:
7
Similarly:
var x = {};
console.log((x["hi"] = 7));
Also outputs 7.
As for the second thing, PrimaryColors is initially undefined.
var x;
console.log(x); // undefined
In a boolean context, undefined evaluates to false:
console.log(!undefined); // true
console.log(!!undefined); // false
Sanity check:
console.log((!undefined) === true); // true
console.log((!!undefined) === false); // true
console.log(undefined === false); // false
This is a common usage of short circuiting. Because PrimaryColors is initially undefined (false), it will pass {} to the function.
PrimaryColors || (PrimaryColors = {})
Maybe this will help.
(function() {})();
This is an 'immediately executing function'. It defines a function as an expression, and then invokes it.
var x = y || y = {};
If a common pattern for initializing something to a default value. If y does not have a value, the 1st part of the or-statement is false, so it executes the 2nd part, which assigns a value to y. The value of that 2nd expression is the new value of y. So x becomes that value of y -- which is the new value if it wasn't already defined.
x[y] = z;
Objects in JS are associative arrays. In other words, string-object pairs, like IDictionary(string,object). This expression is setting the key with value y to the value of z, in the dictionary x;
x[x["a"] = 0] = "a";
So, same thing here, but with a nested expression, which is:
x["a"] = 0;
So that just sets the value of key "a". Nothing fancy. But this is also an expression, whose value is 0. So substitute that in the original expression:
x[0] = "a";
Keys need to be strings, so it's actually the same thing as:
x["0"] = "a";
Which just sets yet another key in the dictionary. Result is that these statements are true:
x["0"] === "a";
x["a"] === 0;
I found this question because I was wondering why use an IIFE at all when you can just init the var with {} right off. The previous answers don’t cover it, but I’ve found my answer in the TypeScript Deep Dive.
The thing is, enums can be split into multiple files. You just have to explicitly initialize the first member of second, third, etc. enums, so this:
enum Colors {
Red,
Green,
Blue
}
enum Colors {
Cyan = 3,
Magenta,
Lime
}
transpiles to this:
var Colors;
(function (Colors) {
Colors[Colors["Red"] = 0] = "Red";
Colors[Colors["Green"] = 1] = "Green";
Colors[Colors["Blue"] = 2] = "Blue";
})(Colors || (Colors = {}));
var Colors;
(function (Colors) {
Colors[Colors["Cyan"] = 3] = "Cyan";
Colors[Colors["Magenta"] = 4] = "Magenta";
Colors[Colors["Lime"] = 5] = "Lime";
})(Colors || (Colors = {}));
As you probably know, redeclaring a variable within the same scope is harmless, but reinitialization is not.
I think they could probably just go:
var Colors;
Colors || (Colors = {});
Colors[Colors["Cyan"] = 3] = "Cyan";
// ...
and skip the closure, but maybe I’m still missing something.
It is used to create an associated map (in other words an object) where you will retrieve the 'name' of the enum value by using the index as key and vice versa. In other words: PrimaryColors["Red"] (or PrimaryColors.Red using dot notation) will yield 0. PrimaryColors[0] (dot notation would be invalid here) will yield "Red".
Understanding the implementation is actually not that hard if we consider three concepts:
The assignment of values to existing variables in javascript evaluates to a value (so it's an expression rather than a statement in spirit)
Object attributes (keys) can be accessed via brackets given their key
Object attributes need to be of type string or Symbol but other values will be propagated to a string if possible.
Therefore:
PrimaryColors[PrimaryColors["Red"] = 0] = "Red";
is equivalent to
const valueToBeUsedAsIndex = PrimaryColors.Red = 0; // assignment evaluates to 0, i. e. valueToBeUsedAsIndex has value 0
PrimaryColors[valueToBeUsedAsIndex] = "Red"; // PrimaryColors[0] is "Red". Technically this assignment yields a value too ("Red" in this particular case) but the value is discarded as it's not needed anymore
// at this point PrimaryColors looks like this: { Red: 0, "0": "Red" }
Lots of great answers here and thank you all, but I would like to add more for simplicity and for my personal reference, and for others who have the same learning structure in breaking things down to the last bit, I will be skipping the Immediately-invoked Function Expressions (IIFE) ill image we all already know that part
now let me break it step by step
PrimaryColors = {} // right now this is an empty object
PrimaryColors[PrimaryColors["Red"]=0] = 'Red'
the most important part here is many don't know that when u set a value to an object
you get a returned value
like below
pp = {}
dd = pp['red']=0
0 // as you can see here the result of the assignment is returned
//now dd is assigned this returned value
// this is the same thing going on here.
> dd
0
we are setting the returned value as the key which is 0 which the javascript hashing algorithm converts to a string and returns as a string.
I hope everyone understands.
I have recently encountered a nasty issue in JS.
Let say we pass a map, an array of objects to a function f.
var o=[{a:0}];
function f(a){
for(var i in a){
if (a.hasOwnProperty(i)){
a[i]=null;
}
}
return a;
};
var outp=f(o);
alert(outp[0]+" === "+o[0]+" : "+(outp[0]===o[0]));
// here we expect loose equality, and equality in type,
//furthermore it should identically equal as well, and we got right!
But, we can not pass total responsibility of an object to a function as argument, same like in functional paradigm o=(function(o){return o})(), because any kind of modification to o is not referenced!
var o=[];
function ff(a){
return (a=undefined);
};
var outp=ff(o);
alert(outp+" === "+o.constructor+" : "+(outp===o));
// here we expect true, but we got false!
Why is the above described reference loss and
presumably different referencce handling in the second use case,
though in both case, functions got the array argument in the 0. position?
Javascript always passes arguments by value, so this won't work:
function foo(x) {
x = 100;
}
y = 5
foo(y)
y == 100 // nope
However this does work:
function foo(x) {
x.bar = 100;
}
y = {}
foo(y)
y.bar == 100 // yes
In the second snippet x is still passed by value, but this very value is a reference (pointer) to an object. So it's possible in a function to dereference it and access what's "inside" the object.
Javascript objects can be used as maps. The following all is valid code:
var x = {};
x.a = 1;
x['b'] = 2; // the same as x.b = 2;
x[3] = 3; // x.3 won't work, but this syntax works fine. Also, x[3] == x['3'].
x['What, this works too?!?!?'] = 'Yup, it does!';
But today I tested another case which... seems to work, but raises some warning flags in my head because it looks... wrong:
x[null] = 42;
Now, it would be extremely cool if this worked as expected (I won't have to rewrite a bunch of code then), but can I rely on it? Or maybe this is just some undocumented behavior which just happens to work in all modern browsers but might as well cease working on the next release of Google Chrome?
Anything between the property brackets is converted to a string. null becomes "null", which is a valid property.
It's valid ECMAScript 5, but you may run into problems in some versions of Internet Explorer.
This is all fine:
x = {};
x[null] = 42;
x[null];
// 42
x = {"null": 42};
x[null];
// 42
However, IE8 doesn't accept the following with reserved words such as null:
x.null
// Error: Expected identifier
x = {null: 42}
// Expected identifier, string or number
(Both of the above work in Chrome, even with "use strict" enabled.)
I cannot leave comments so I created an answer...
While Rob W is correct his answer is a little misleading. The item between the square brackets is converted to a string using ToString(). So, a[null] only equals a['null'] because ToString( null ) == 'null'
take for instance
var a = 1;
var x = {}
x[a] = 20;
x['1'] = 30; -- this is exactly the same as the previous line and now x[a] == 30
If your environment supports ES6 and you need to be able to store a value for null as well as any arbitrary string then you can use a Map.
const a = new Map();
a.set(null, 'foo')
a.set('null', 'bar')
// Map { null => 'foo', 'null' => 'bar' }
x['null'] = 42;
I would strongly dis-recommend that, though, to avoid confusion.
Property names are strings. Every string will work, even ones that represent reserved identifiers.
Everything that's not a string will be converted into a string (by calling the object's toString() method):
a = ['FOO']; // an array
o = {}; // an object
o[a] = 'foo'; // using a as the property name
// o now is:
{
FOO: 'foo'
}