On arrow function bodies, whats the difference between using brackets, placing direclty the condition, or using pharentesis? [duplicate] - javascript

This question already has answers here:
When do we have to use () and {} in ES6 Arrow Functions
(2 answers)
Arrow function without curly braces
(9 answers)
Curly Brackets in Arrow Functions
(3 answers)
What does the comma operator do in JavaScript?
(5 answers)
Closed 2 months ago.
In my years of JS development I've seen the following examples:
let a = () => console.log("a");
let b = () => { console.log("b"); }
let c = () => (console.log("c"));
I know the difference between the first two options, but the last one always seem'd a little off to me. I've also tried to do the following, which surprisingly works:
let c = () => (console.log("c1"), console.log("c2")); // Outputs both console logs.
And also this:
let c = () => (1, 2, 3, 4 ,5);
let x = c(); // 5
I've searched about this way of defining function bodies, yet I'm not satisfied with what I have found since every example I've stumbled on was poorly explained.
Can anyone please explain to me a bit more in-depth the difference between the three examples, and also what's special about the last one?
Thanks in advance.

let c = () => (console.log("c"))
I know the difference between the first two options, but the last one always seem'd a little off to me.
Arrow syntax allows you to return the value of the expression directly without having to enclose in curly braces and using a return statement. In the example above, enclosing the value (returned by console.log) in brackets does not change its value.
And also this:
let c = () => (1, 2, 3, 4, 5);
What you are seeing is the comma operator in action. It will return the value of the last operand, which is why c returns 5.
I've also tried to do the following, which surprisingly works:
let c = () => (console.log("c1"), console.log("c2")); // Outputs both console log
In this case, both expressions are evaluated, and thus both strings are logged. However, the expression yields a value of undefined, since console.log returns undefined.

First of all, you're talking specifically about arrow (=>) functions. Traditional functions must have a body enclosed in { }.
An arrow function can have a traditional body enclosed in { }. It can also have a single expression as its body, in which case the result of evaluating the expression is implicitly the return value. Given that, note that any expression in JavaScript in any context can be enclosed in parentheses ( ) and the value is the same as the enclosed expression.
The comma effect is the operator in the JavaScript expression grammar ,, which allows disparate expressions to be chained together into a list that, syntactically, is still a single expression. The comma operator is useful sometimes because expressions can have side-effects; for example, a function call is an expression, and a function call may do almost anything. The value of a list of expressions in a comma operator list is the value of the last one of the expressions after evaluation.

Related

What is this ES6 syntax/style of function declaration called? [duplicate]

This question already has answers here:
java-script arrow function returns (x++,x) [duplicate]
(3 answers)
What does the comma operator do in JavaScript?
(5 answers)
When is the comma operator useful?
(15 answers)
Closed 9 months ago.
I tried looking at MDN on arrow functions, that links to an article ES6 In Depth: Arrow functions and the ECMAScript grammar. I didn't find an example of this style of function body.
See takeStockForBowl in example code below.
Question, what would this style of function definition be called?
Maybe it's a repurposing of a more basic JavaScript syntax and I just don't see it. Apologies if it's obvious.
const takeStockForBowl = bowl => ( // open paren
takeForBowl('protein', bowl), // side effect 1
takeForBowl('grain', bowl), // side effect 2
takeForBowl('veg', bowl), // ...
bowl.supplied = true, // side effect n
bowl // result
) // close paren
First of all, takeStockForBowl is really hard to read.
To understand what's happening here, we need to understand two things:
Arrow functions
Comma operator
Basically what the author has done here is avoided writing the following:
Explicit return statement
Curly braces for the function body
by taking advantage (or abusing) of implicit return in arrow function and the comma operator.
What comma operator does is it evaluates each of its operands from left to right and returns the value of the last operand which in this case is bowl.
More readable version of this function is:
const takeStockForBowl = bowl => {
takeForBowl('protein', bowl);
takeForBowl('grain', bowl);
takeForBowl('veg', bowl);
bowl.supplied = true;
return bowl;
}

Does return is added implicitly in a callback function? [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 2 years ago.
I have a code (attached screenshot) that in one place it is written explictiy reutrn inside a callback, and in another one it isn't. I'm trying to understand what is the reason for it? In my opinion return statement should be added also in the first one. Am i wrong?
There is a return in the first one. Read this about arrow functions
"(...) If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword" - https://www.w3schools.com/js/js_arrow_function.asp
What you're seeing is a property of the arrow function: if the braces are omitted the result of the following statement is returned automatically.
input => output is the same as input => { return output; }.
Note that this behavior differs from regular functions, as these two functions do not both return a result:
function a(input) { return 1 };
function b(input) { 1 };
a() // 1
b() // undefined

How to print JavaScript array with set of pairs inside array [duplicate]

This question already has answers here:
JavaScript expressions, comma delimited within parentheses [duplicate]
(3 answers)
Closed 2 years ago.
I was going through documentation of JavaScript about arrays and objects.I found one unique query about arrays
var a= [1,2,3]
console.log(a) // give [1,2,3]
var b = [(1,2) , (3,4) , (5,6)]
console.log(b) // gives [2,4,6]
I didn't understand the logic behind the same.It just ran over my mind.If we do same thing in python
a = [(1,2),(3,4)]
print(a) // [(1,2),(3,4)]
Can some one explain the same and can someone explain me how to get the same output in JavaScript like the way I got in python.How to iterate through all the elements in array in javascript
I'm not a Python programmer, but those parentheses differ in their functionality between Python and JavaScript.
I understand in Python they indicate a tuple literal. In JavaScript, they merely group things they say "execute each statement and return the last one." That's why you only see some items in your JS arrays.
See also https://stackoverflow.com/a/25280412/1371131
What you have encountered is the comma operator.
When there is no other context, a , in an expression behaves like an operator just like + or = or / etc.
The comma operator behaves as follows:
evaluate the first expression
ignore the result of the first expression
evaluate the second expression
return the value of the second expression
Thus the following code:
a = 1,2;
b = 1,2,3,4;
will result in a being assigned the value 2 and b assigned the value 4.
This may seem kind of silly because we already have ; but the comma operator is useful if you need more than one thing to happen in a single expression context. For example if you need more than one thing to happen in one of the conditions of a for loop you cannot use ; because that is used to separate the conditional expressions. The comma operator comes to the rescue:
for (let a = 0, b = 0; a < 10; a++, b++) { //...
// ^ ^
// | |____ two things happen here
// |_______________________________ and here
So (1,2) is just another way to write 2.
Therefore [(1,2) , (3,4) , (5,6)] and [2,4,6] is the same array.
Just like [1+1, 2+2, 3+3] and [2,4,6] is the same array.
They are just different ways to write [2,4,6]. The same way you cannot loop through the array and extract 1+ from [1+1, 2+2, 3+3] you cannot loop through the array and extract (1, from [(1,2) , (3,4) , (5,6)].
If you really need an array of pairs you need to use an array of arrays:
a = [[1,2],[3,4],[5,6]]

ES6 Arrow function with brackets [duplicate]

This question already has answers here:
Curly Brackets in Arrow Functions
(3 answers)
Why doesn't my arrow function return a value?
(1 answer)
Closed 6 years ago.
I came across a little problem in my code which was kind of confusing to me and hope someone could explain why it does the things it does.
Code 1
sendText(){
return this.http.get('/api')
.map((response:Response) => response.json());
}
Code 2
sendText(){
return this.http.get('/api').map((response:Response) => {
response.json();
});
}
The key difference between these two code is that in Code 2 I placed the brackets after the arrow function to add my tasks inside those brackets and in Code 1 I took the brackets out and place the task on one line.
My question is why does my object coming from the server side coming back as undefined in Code2 with the subscribe method that angular2 provided while Code1 returns the object I suspect.
(response:Response) => response.json()
This is shorthand for this:
(response:Response) => { return response.json(); }
The {} let you add multiple statements inside the block. Without them, the function just runs the one statement and returns its value.
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

JavaScript => operator [duplicate]

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 7 years ago.
I was looking at some frontend guidelines on GitHub and saw the following code sample:
// good
const createDivs = howMany => {
if (!howMany) return;
document.body.insertAdjacentHTML("beforeend", "<div></div>");
return createDivs(howMany - 1);
};
createDivs(5);
What does the => do and what is it called? I have never seen this idiom before. I tried looking it up but do not know its name and the MDN documentation does not show it.
From the MDN documentation on arrow functions:
An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous.
Besides the fact that they are a more concise way of writing an anonymous function, arrow functions have the benefit of binding this in the function expression. Thus, the pattern typically used with bind:
document.addEventListener('click', function myHandler (event) {
console.log(event);
}.bind(this));
becomes
document.addEventListener('click', (event) => console.log(event));
What you're looking at is an arrow function expression. It's a shorter way of writing a function expression.
This example from Mozilla illustrates the advantage of defining a function with an arrow expression:
var a = [
"Hydrogen",
"Helium",
"Lithium",
"Beryl­lium"
];
var a2 = a.map(function(s){ return s.length });
var a3 = a.map( s => s.length );
Observe that s => s.length is shorter than the traditional equivalent function(s){ return s.length }. It will be easier to read, too, once we get used to seeing this form.

Categories