Related
I'm new to both ES6 and React and I keep seeing arrow functions. Why is it that some arrow functions use curly braces after the fat arrow and some use parentheses?
For example:
const foo = (params) => (
<span>
<p>Content</p>
</span>
);
vs.
const handleBar = (e) => {
e.preventDefault();
dispatch('logout');
};
The parenthesis are returning a single value, the curly braces are executing multiple lines of code.
Your example looks confusing because it's using JSX which looks like multiple "lines" but really just gets compiled to a single "element."
Here are some more examples that all do the same thing:
const a = (who) => "hello " + who + "!";
const b = (who) => ("hello " + who + "!");
const c = (who) => (
"hello " + who + "!"
);
const d = (who) => (
"hello "
+ who
+ "!"
);
const e = (who) => {
return "hello " + who + "!";
};
You will also often see parenthesis around object literals because that's a way to avoid the parser treating it as a code block:
const x = () => {} // Does nothing
const y = () => ({}) // returns an object
One can also use curly braces to prevent a single line arrow function from returning a value -- or to make it obvious to the next developer that a single line arrow function shouldn't, in this case, be returning anything.
For example:
const myFunc = (stuff) => { someArray.push(stuff) }
const otherFunc = (stuff) => someArray.push(stuff)
console.log(myFunc()) // --> logs undefined
console.log(otherFunc()) // --> logs result of push which is new array length
Parenthesis are used in an arrow function to return an object.
() => ({ name: 'YourName' }) // This will return an object
That is equivalent to
() => {
return { name : 'YourName' }
}
Actually in a briefcase when somebody uses braces in an arrow function declaration, it is equal to below:
const arrow = number => number + 1;
|||
const arrow = (number) => number + 1;
|||
const arrow = (number) => ( number + 1 );
|||
const arrow = (number) => { return number + 1 };
Parenthesis has an implicit return statement while curly braces you need an explicit return statement
If you use curly braces after the arrow to define the function body, you have to use the 'return' keyword to return something.
For example:
const myFun1 = (x) => {
return x;
}; // It will return x
const myFun2 = (x) => {
x;
}; // It will return nothing
If you use the parenthesis, you don't need to mention the 'return' keyword.
For example:
const myFunc1 = (x) => x; // It will return x
const myFunc2 = (x) => (x); // It will also return x
In your first example, the right-hand side of the arrow function shows a single expression that is enclosed by a grouping operator:
const foo = (params) => (
<span>
<p>Content</p>
</span>
);
A similar comparable case would be the following:
const foo = (params) => (<span><p>Content</p></span>);
A distinction, in the above cases using single expressions, is that the right-hand side is the returned value of the function.
On the other hand, if you use curly braces, JavaScript will understand that as a statement:
const foo = (params) => {} // this is not an object being returned, it's just an empty statement
Therefore, using statement is a good start for you to have code in it, multiple lines, and it will require the use of "return" if the function is intended to return value:
const foo = (params) => {
let value = 1;
return value;
}
In case you wanted to return an empty object in the shortest form:
const foo = (params) => ({})
See tests
To answer a duplicate post(question posted here), just for reference for others:
var func = x => x * x;
// concise body syntax, implied "return"
var func = (x, y) => { return x + y; };
// with block body, explicit "return" needed
For reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body
Also note:
If you are returning an object literal as the result from a fat arrow function, then you must enclose the object in parentheses, e.g., myFunc = () => ({ data: "hello"}). You will receive an error if you omit the parentheses because the build tools will assume that the curly braces of the object literal are the start and end of a function body.
Every function has 2 aspects.
First of them is that each one, not just the arrow functions, has an execution context (a block scope) in which the variables are created and used.
In other words, inside the curly braces { ... } of the function, what is declared and assigned there, stays there and is not visible to the outside functions / or variables.
For example, when writing something as
let x = 100;
function doSomething() {
let x = 50;
console.log(x);
}
doSomething(); // 50
console.log(x); // 100
both values are displayed in console (instead of 'x from outside just being replaced by x from inside the function').
You see that despite of let not usually allowing other variable x to be declared again (with the same name x), in this case, because the second x is declared and initialized inside the { ... }, it does not alter the outside one, which also happens because after the function doSomething is called, the x from inside of it is created, assigned, printed in console and then destroyed (deleted from the memory). So that process happens every time we call that function by running doSomething() .
So this is the first aspect to take into consideration when understanding the functions: they execute then forget the values created by the code inside their curly braces.
Because of it, it's easier to understand their second aspect -- as functions cannot just work isolated from the others, they need to also send data to the others, so they have some 'reporting aspect' used to externalize some part of the results computed inside their curly braces, which is exactly why the return statement exists.
Return exists in each function, even in the console.log or alert(), even in doSomething(), but in these cases where we didn't explicitly set something for it, it is always 'return undefined'.
Therefore it isn't necessary to write it, but instead know that where you don't return something specific, the function itself will do it for you by returning undefined.
When you write (or use) a function meant just to execute something, it will also return undefined. Always.
You can check that thing with every function which (apparently) has no declared return:
let x = alert(100);
console.log(x); // undefined
let y = doSomething(); // console prints 50
console.log(y); // 50, then undefined --- 2 lines
console.log(alert('Hello')); // undefined
console.log(console.log('Okay')); // Okay , then undefined
Why is that?
Because alert() which is a method of global object window (in browser) (so it is actually window.alert() ) and also console.log() (which is the same with window.console.log() , too), execute something (printing in an alert box or in the console whatever is in between the () AND THEN return undefined).
Now, coming back to the arrow functions, they are not just some new way of notation for writing the functions but they also have some specific features.
First, if you only have a parameter between the () in an arrow function, you can write it without the parentheses.
Second, if inside the curly braces there's a single statement, you can omit as well the curly braces.
Third one, if the single statement is a return statement, you can omit the word return.
Somehow, using these we could transform many usual functions into arrow functions if needed:
function doSomething() {let x = 50; console.log(x);} // as function declaration
let doSomething = function() {let x = 50; console.log(x);}; // as function expression, which is an anonymous function assigned to the variable 'doSomething'
let doSomething = () => {let x = 50; console.log(x);}; // as arrow function
// let's transform it further
let doSomething = () => {console.log(50)}; //
// that is equivalent to ---- let doSomething = () => {console.log(50); return undefined};
// or even to ---- let doSomething = () => {return ( console.log(50) ) };
// because anyways, *console.log* has *return undefined* in it, as explained above
//which is the same as ---- let doSomething = () => {return console.log(50) };
// let's now apply the rules 2 and 3 from above, one by one:
let doSomething = () => return console.log(50);
let doSomething = () => console.log(50);
// Obviously, this just shows how we could rewrite many usual functions (functions declarations) into arrow functions
// we can do that safely if we don't have any **this** involved in the functions, of course
// also, from all lines of code above only one must remain, for example the last one.
// the last one, despite only having ---- console.log(50) --- as the execution aspect, it also ---- returns undefined ---- as well
// obviously ---- console.log( typeof doSomething ); // function
// while ---- console.log( typeof doSomething() ); // undefined
If an arrow function has 2 or more parameters, we cannot omit the parentheses around them:
function sum(a, b) {let total = a + b; return total}
let sum = function(a, b) {let total = a + b; return total};
// or
let sum = (a, b) => {let total = a + b; return total};
// or
let sum = (a, b) => {return a + b};
// or
let sum = (a, b) => a + b;
For simple operations as above, the fat arrow sign '=>' can be "read" as is transformed into, in other words, a and b is (are) transformed into a + b.
Opposite to that, there are also functions that validate some data (for example checking the data type, etc), like this one
let isNumber = x => typeof x === "number";
// or
let isNumber = (x) => {return (typeof x === "number")};
// obviously,
isNumber("Hello, John!"); // false
Those DON'T transform the data, and thus the arrow sign can be read something more as with the condition that, or similar.
In other words, a function like
let double = x => x * 2 // 'double' is a function that transforms x into x*2
is not the same as a checking one (mostly used in filters, sort, and other kind of validating functions, usually as callback function, etc)
let isArray = arr => Array.isArray(arr) // that last one already returns boolean by itself, no need to write return (Array.isArray() etc)
Last thing to know about return is that when you write code in multiple lines, the ASI (Automatic Semicolon Insertion) will insert a ';' after return if you mistakenly press enter after writing the return word, which will break the code, therefore instead of
return
a+b;
your code will behave as
return;
a+b;
so you better write the code with parentheses as here:
return (
a + b
);
as explained in MDN website here, too.
This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 6 years ago.
I have the following arrow function
if( rowCheckStatuses.reduce((a, b) => a + b, 0) ){}
rowCheckStatuses is an array of 1's and 0's, this arrow function adds them all up to produce a number. This number acts as a boolean to determine whether or not there is at least one "1" in the array.
The issue is, I don't really understand how arrow functions work, and my IDE thinks it's bad syntax and refuses to check the rest of my document for syntax errors.
How would I go about converting this to a regular function to alleviate both issues?
An arrow function can usually be converted by replacing
(<args>) => <body>
with
function(<args>) { return <body>; }
So yours would be
rowCheckStatuses.reduce(function(a, b) { return a + b; }, 0)
There are exceptions to this rule so it's important that you read up on arrow functions if you want to know all of the differences. You should also note that arrow functions have a lexical this.
You can refactor it as:
if( rowCheckStatuses.reduce(function(a, b){return a + b}, 0)
The initial accumulator isn't necessary (unless you expect the array to be empty sometimes), it could be:
if( rowCheckStatuses.reduce(function(a, b){return a + b})
This number acts as a boolean to determine whether or not there is at least one "1" in the array
It might be faster (and clearer) to use:
if( rowCheckStatuses.some(function(a){return a == 1}))
which will return true if there are any 1s in rowCheckStatuses and will return as soon as one is encountered. Another alternative is indexOf:
if( rowCheckStatuses.indexOf(1) != -1)
Lots of alternatives.
Replacing arrow functions with regular functions is usually unproblematic:
var f = x => y;
var g = function(x) { return y; }
Or, in your specific example:
rowCheckStatuses.reduce((a, b) => a + b, 0);
rowCheckStatuses.reduce(function(a, b) { return a + b; }, 0);
However, be aware of the exceptions:
Arrow functions don't bind a this value. Accessing this in an arrow function might thus return the value of the enclosing execution context's this:
function MyClass() {}
MyClass.prototype.f = () => this;
MyClass.prototype.g = function() { return this; }
myClass = new MyClass();
console.log(myClass.f()); // logs `Window`
console.log(myClass.g()); // logs `myClass`
Arrow functions also don't have access to a local arguments object. Accessing arguments in an arrow function might e. g. return the arguments of an enclosing function:
function test() {
var f = () => arguments;
var g = function() { return arguments; }
console.log(f()); // logs test's arguments
console.log(g()); // logs g's arguments
}
test('x');
The same holds for new.target and super. See also What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?
I came across to the following JS code (ES5)
and I don't really I understand what is the meaning of the this variable.
function multiply(a,b){
return a * b;
}
var multipleByThree = multiply.bind(this,3);
multipleByThree(10) // outputs 30
I do understand that the bind copies the multiply function and that 'a' parameter of it, will have the value 3. But what is the purpose of the this variable?
Can you help me out please?
The this variable that you are providing to .bind() is the context. In your case, this refers to the global object space.
Here's an example of how this works:
var message = 'within global context';
function multiply(a,b){
console.log(this.message);
return a * b;
}
var someOtherContext = {
message: 'within some other context'
};
var multipleByThree = multiply.bind(this,3);
var multipleByThreeOtherContext = multiply.bind(someOtherContext, 3);
console.log(multipleByThree(10))
console.log(multipleByThreeOtherContext(10))
By changing the context that multiply executed within, we can change what variables it references.
The first argument to bind must be the thisArg:
fun.bind(thisArg[, arg1[, arg2[, ...]]])
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
That is, whatever the keyword this inside multiply will refer to. Since multiply doesn't use this at all, it's irrelevant what it refers to. You must still pass something as the first argument to bind, so likely the developer simply chose this (whatever that refers to in this code is unknown to us), but they could just as well have used false, null or anything else.
In javascript this is some kind of "reserved keyword" which refers to current object of the scope.
If this used outside of any object - it refers to window object.
Inside eventhandlers this refers to the DOM object which raised an event.
bind function provide possibility to define which object this will refer inside bound function.
For example if you using this inside function
const calculate = function (price, amount) {
return (price * amount) - this.discount;
};
You can bound a function with predefined this
const calculateWithDiscount = calculate.bind({ discount: 100 });
const total = calculateWithDiscount(1000, 2); // return 1900
When you bound function which doesn't use this object, you can easily pass null there, which clearly "tell" other developers your intents about using this in the function.
const add = function (a, b) {
return a + b;
};
const add5 = add.bind(null, 5);
const result = add5(19); // return 24
bind Method (Function) (JavaScript)
For what it's worth, you can do currying without relying upon Function.prototype.bind
Once you stop relying upon this in JavaScript, your programs can start looking like beautiful expressions
const curry = f => x => y =>
f (x,y)
const mult = (x,y) =>
x * y
const multByThree =
curry (mult) (3)
console.log (multByThree (10)) // 30
For a more generic curry implementation that works on functions of varying arity
const curry = (f, n = f.length, xs = []) =>
n === 0
? f (...xs)
: x => curry (f, n - 1, xs.concat ([x]))
If you want to bellyache about the exposed private API, hide it away with a loop – either way, this is not required to write functional programs in JavaScript
const loop = f =>
{
const recur = (...values) =>
f (recur, ...values)
return f (recur)
}
const curry = f =>
loop ((recur, n = f.length, xs = []) =>
n === 0
? f (...xs)
: x => recur (n - 1, xs.concat ([x])))
it fixes 3 as the first argument, the arguments of the new function will be preceded by 3
function multiply(a,b){
console.log(a, b);
console.log(arguments)
return a * b;
}
var multipleByThree = multiply.bind(console.log(this),3);
console.log(multipleByThree(10)) // outputs 30
console.log(multipleByThree(10, 15)) // outputs 30
passing this would provide a copy of this(i.e the global object) with the preceded arguments list
For more information check out the MDN docs
In the context of Currying the this object in the code presented has no purpose other than as a placeholder. You could replace this with the string "cats" if you wanted and still get the same result. It is simply there to occupy the first argument position and I think it is very misleading to use it in the context of
either currying or partial application when using bind. It is better to replace it with the null keyword.
In the case of this example it will pass in the global object and the rest of the code will simply ignore that value since the keyword 'this' is not present within the multiply function itself.
MDN shows a use case, visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
and scroll to the section headed Partially applied functions.
ES6 (aka es2015) has improved on the way this code is written by using arrow functions and the code can now be reduced to the following
const multiply = a => b => a * b
const multiplyByThree = multiply(3)
const result = multiplyByThree(10)
console.log(result)
// => 30
I'm new to both ES6 and React and I keep seeing arrow functions. Why is it that some arrow functions use curly braces after the fat arrow and some use parentheses?
For example:
const foo = (params) => (
<span>
<p>Content</p>
</span>
);
vs.
const handleBar = (e) => {
e.preventDefault();
dispatch('logout');
};
The parenthesis are returning a single value, the curly braces are executing multiple lines of code.
Your example looks confusing because it's using JSX which looks like multiple "lines" but really just gets compiled to a single "element."
Here are some more examples that all do the same thing:
const a = (who) => "hello " + who + "!";
const b = (who) => ("hello " + who + "!");
const c = (who) => (
"hello " + who + "!"
);
const d = (who) => (
"hello "
+ who
+ "!"
);
const e = (who) => {
return "hello " + who + "!";
};
You will also often see parenthesis around object literals because that's a way to avoid the parser treating it as a code block:
const x = () => {} // Does nothing
const y = () => ({}) // returns an object
One can also use curly braces to prevent a single line arrow function from returning a value -- or to make it obvious to the next developer that a single line arrow function shouldn't, in this case, be returning anything.
For example:
const myFunc = (stuff) => { someArray.push(stuff) }
const otherFunc = (stuff) => someArray.push(stuff)
console.log(myFunc()) // --> logs undefined
console.log(otherFunc()) // --> logs result of push which is new array length
Parenthesis are used in an arrow function to return an object.
() => ({ name: 'YourName' }) // This will return an object
That is equivalent to
() => {
return { name : 'YourName' }
}
Actually in a briefcase when somebody uses braces in an arrow function declaration, it is equal to below:
const arrow = number => number + 1;
|||
const arrow = (number) => number + 1;
|||
const arrow = (number) => ( number + 1 );
|||
const arrow = (number) => { return number + 1 };
Parenthesis has an implicit return statement while curly braces you need an explicit return statement
If you use curly braces after the arrow to define the function body, you have to use the 'return' keyword to return something.
For example:
const myFun1 = (x) => {
return x;
}; // It will return x
const myFun2 = (x) => {
x;
}; // It will return nothing
If you use the parenthesis, you don't need to mention the 'return' keyword.
For example:
const myFunc1 = (x) => x; // It will return x
const myFunc2 = (x) => (x); // It will also return x
In your first example, the right-hand side of the arrow function shows a single expression that is enclosed by a grouping operator:
const foo = (params) => (
<span>
<p>Content</p>
</span>
);
A similar comparable case would be the following:
const foo = (params) => (<span><p>Content</p></span>);
A distinction, in the above cases using single expressions, is that the right-hand side is the returned value of the function.
On the other hand, if you use curly braces, JavaScript will understand that as a statement:
const foo = (params) => {} // this is not an object being returned, it's just an empty statement
Therefore, using statement is a good start for you to have code in it, multiple lines, and it will require the use of "return" if the function is intended to return value:
const foo = (params) => {
let value = 1;
return value;
}
In case you wanted to return an empty object in the shortest form:
const foo = (params) => ({})
See tests
To answer a duplicate post(question posted here), just for reference for others:
var func = x => x * x;
// concise body syntax, implied "return"
var func = (x, y) => { return x + y; };
// with block body, explicit "return" needed
For reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body
Also note:
If you are returning an object literal as the result from a fat arrow function, then you must enclose the object in parentheses, e.g., myFunc = () => ({ data: "hello"}). You will receive an error if you omit the parentheses because the build tools will assume that the curly braces of the object literal are the start and end of a function body.
Every function has 2 aspects.
First of them is that each one, not just the arrow functions, has an execution context (a block scope) in which the variables are created and used.
In other words, inside the curly braces { ... } of the function, what is declared and assigned there, stays there and is not visible to the outside functions / or variables.
For example, when writing something as
let x = 100;
function doSomething() {
let x = 50;
console.log(x);
}
doSomething(); // 50
console.log(x); // 100
both values are displayed in console (instead of 'x from outside just being replaced by x from inside the function').
You see that despite of let not usually allowing other variable x to be declared again (with the same name x), in this case, because the second x is declared and initialized inside the { ... }, it does not alter the outside one, which also happens because after the function doSomething is called, the x from inside of it is created, assigned, printed in console and then destroyed (deleted from the memory). So that process happens every time we call that function by running doSomething() .
So this is the first aspect to take into consideration when understanding the functions: they execute then forget the values created by the code inside their curly braces.
Because of it, it's easier to understand their second aspect -- as functions cannot just work isolated from the others, they need to also send data to the others, so they have some 'reporting aspect' used to externalize some part of the results computed inside their curly braces, which is exactly why the return statement exists.
Return exists in each function, even in the console.log or alert(), even in doSomething(), but in these cases where we didn't explicitly set something for it, it is always 'return undefined'.
Therefore it isn't necessary to write it, but instead know that where you don't return something specific, the function itself will do it for you by returning undefined.
When you write (or use) a function meant just to execute something, it will also return undefined. Always.
You can check that thing with every function which (apparently) has no declared return:
let x = alert(100);
console.log(x); // undefined
let y = doSomething(); // console prints 50
console.log(y); // 50, then undefined --- 2 lines
console.log(alert('Hello')); // undefined
console.log(console.log('Okay')); // Okay , then undefined
Why is that?
Because alert() which is a method of global object window (in browser) (so it is actually window.alert() ) and also console.log() (which is the same with window.console.log() , too), execute something (printing in an alert box or in the console whatever is in between the () AND THEN return undefined).
Now, coming back to the arrow functions, they are not just some new way of notation for writing the functions but they also have some specific features.
First, if you only have a parameter between the () in an arrow function, you can write it without the parentheses.
Second, if inside the curly braces there's a single statement, you can omit as well the curly braces.
Third one, if the single statement is a return statement, you can omit the word return.
Somehow, using these we could transform many usual functions into arrow functions if needed:
function doSomething() {let x = 50; console.log(x);} // as function declaration
let doSomething = function() {let x = 50; console.log(x);}; // as function expression, which is an anonymous function assigned to the variable 'doSomething'
let doSomething = () => {let x = 50; console.log(x);}; // as arrow function
// let's transform it further
let doSomething = () => {console.log(50)}; //
// that is equivalent to ---- let doSomething = () => {console.log(50); return undefined};
// or even to ---- let doSomething = () => {return ( console.log(50) ) };
// because anyways, *console.log* has *return undefined* in it, as explained above
//which is the same as ---- let doSomething = () => {return console.log(50) };
// let's now apply the rules 2 and 3 from above, one by one:
let doSomething = () => return console.log(50);
let doSomething = () => console.log(50);
// Obviously, this just shows how we could rewrite many usual functions (functions declarations) into arrow functions
// we can do that safely if we don't have any **this** involved in the functions, of course
// also, from all lines of code above only one must remain, for example the last one.
// the last one, despite only having ---- console.log(50) --- as the execution aspect, it also ---- returns undefined ---- as well
// obviously ---- console.log( typeof doSomething ); // function
// while ---- console.log( typeof doSomething() ); // undefined
If an arrow function has 2 or more parameters, we cannot omit the parentheses around them:
function sum(a, b) {let total = a + b; return total}
let sum = function(a, b) {let total = a + b; return total};
// or
let sum = (a, b) => {let total = a + b; return total};
// or
let sum = (a, b) => {return a + b};
// or
let sum = (a, b) => a + b;
For simple operations as above, the fat arrow sign '=>' can be "read" as is transformed into, in other words, a and b is (are) transformed into a + b.
Opposite to that, there are also functions that validate some data (for example checking the data type, etc), like this one
let isNumber = x => typeof x === "number";
// or
let isNumber = (x) => {return (typeof x === "number")};
// obviously,
isNumber("Hello, John!"); // false
Those DON'T transform the data, and thus the arrow sign can be read something more as with the condition that, or similar.
In other words, a function like
let double = x => x * 2 // 'double' is a function that transforms x into x*2
is not the same as a checking one (mostly used in filters, sort, and other kind of validating functions, usually as callback function, etc)
let isArray = arr => Array.isArray(arr) // that last one already returns boolean by itself, no need to write return (Array.isArray() etc)
Last thing to know about return is that when you write code in multiple lines, the ASI (Automatic Semicolon Insertion) will insert a ';' after return if you mistakenly press enter after writing the return word, which will break the code, therefore instead of
return
a+b;
your code will behave as
return;
a+b;
so you better write the code with parentheses as here:
return (
a + b
);
as explained in MDN website here, too.
I have been reviewing other people's code and while ES2015 on the whole is taking some getting use to, however, I keep on getting stuck with Destructuring.
Previously, In Javascript, the Curly Brackets {} were either used for blocks or objects. e.g.
// Curly Brackets Block
If () {
...
}
// Curly Brackets in Obj
var obj = {
a : 1,
...
}
However, in destructuring, we see again and again the following syntax:
let a = ({ a, b }) => {
}
My question, is the arguments container an actual object or just a block?
Please explain whether the following be the same as the code above:
let a = ( a, b ) => {
}
EDIT: My understanding (so far) from reading Axel Rauschmayers article on Destruturing is that we are merely mapping the props. into a new Obj always? I.e:
let a = { first : a, second : b } = AnObj;
===
a.a === AnObj.first;
a.b === AnObj.second;
Is the above correct? Is an obj always instantiated? However, that doesn't make sense as in the above function, the object thus created for the props would be an anonymous object, right?
Many thanks,
No, the curly braces in destructuring do form neither a block nor an object literal.
They definitely are not a block because they are not a statement (and don't contain a statement list), they are an expression like an object literal. In fact they even do have the same syntax as an object literal, the only difference is that they are in the position of an assignment target (left hand side of an assignment operator) or a function parameter.
Is let a = ({ a, b }) => {…} the same as let a = ( a, b ) => {…}?
No, really not. Both parameter lists do declare variables a and b for the function scope, but the first function expects an object with properties .a and .b while the second function expects two arguments.
My understanding is that we are merely mapping the properties into a new obj?
No. There is no new object created/instantiated. There is only the object that you pass in (the right hand side). And it is destructured - "pulled apart" - into pieces that are then assigned to the various sub-targets (variables, property references).
To write
a.b = anObj.first;
a.c = anObj.second;
with a destructuring assignment you'd use
({first: a.b, second: a.c}) = anObj;
(the parenthesis are necessary to distinguish the expression from a block).
The more common use case is for variable initialisations however. You can shorten
let b = anObj.first,
c = anObj.second;
to
let {first: b, second: c} = anObj;
And also there's a shorthand when the variable has the same name as the property, so
let first = anObj.first,
second = anObj.second;
is equivalent to
let {first, second} = anObj;
Is let a = { first : a, second : b } = anObj; correct?
No, that doesn't make much sense. It would desugar to
let a;
a = anObj.first;
b = anObj.second;
a = anObj;
It is for destructuring:
var obj = {a: 1, b: 2},
add = ({a, b}) => a + b;
console.log(add(obj)); //3
So basically to the statements inside the function it would appear there are 2 arguments, but when you call it you only pass an object.