When should I use a return statement in ES6 arrow functions
Jackson has partially answered this in a similar question:
Implicit return, but only if there is no block.
- This will result in errors when a one-liner expands to multiple lines and the programmer forgets to add a
return
.- Implicit return is syntactically ambiguous.
(name) => {id: name}
returns the object{id: name}
... right? Wrong. It returnsundefined
. Those braces are an explicit block.id:
is a label.
I would add to this the definition of a block:
A block statement (or compound statement in other languages) is used to group zero or more statements. The block is delimited by a pair of curly brackets.
Examples:
// returns: undefined
// explanation: an empty block with an implicit return
((name) => {})()
// returns: 'Hi Jess'
// explanation: no block means implicit return
((name) => 'Hi ' + name)('Jess')
// returns: undefined
// explanation: explicit return required inside block, but is missing.
((name) => {'Hi ' + name})('Jess')
// returns: 'Hi Jess'
// explanation: explicit return in block exists
((name) => {return 'Hi ' + name})('Jess')
// returns: undefined
// explanation: a block containing a single label. No explicit return.
// more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
((name) => {id: name})('Jess')
// returns: {id: 'Jess'}
// explanation: implicit return of expression ( ) which evaluates to an object
((name) => ({id: name}))('Jess')
// returns: {id: 'Jess'}
// explanation: explicit return inside block returns object
((name) => {return {id: name}})('Jess')
Does the arrow function have to always return a value?
No, (arrow) functions don't have to return anything but when function is not supposed to be void (i.e return value is expected), it's a good practice to return from every path/return some kind of default value if every other path fails.
const getCookie = name => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length == 2) {
return parts
.pop()
.split(';')
.shift();
}
// default return, for example:
return false;
};
Can I omit Return value in arrow function in JavaScript?
You only need to return
something if that returned value will be used somewhere. In the case of onSubmit
, there is no need to return
anything. That (arrow) function is simply running some code when the form is submitted.
In point B in your question, yes, you can remove return
if nothing needs to be done with the returned result of toggleTodo(todo.id)
.
Bitwise operation and arrow function return statement
Is there a way to make
addNeighbour
proceed as a void method (I couldn't find a way to not returnnum
)?
No. If you don't return the result, you cannot assign it back to num
. And you cannot pass a reference to the let num
(or any other) variable that the function should read from and store into.
Is there a better way to perform
addNeighbour
operations
Yes. Adding 1
at the second-least significant bit position is just the same as adding 2
at the least signification position. Replace your code with
num += 2;
Put in other terms,
(((num >> 1) + 1) << 1) | (num & 1)
≡ (((num >> 1) << 1) + (1 << 1)) | (num & 1)
≡ ((num & ~1) + (1 << 1)) | (num & 1)
≡ ((num & ~1) | (num & 1)) + (1 << 1)
≡ num + (1 << 1)
Arrow Function Created In An Object Returns undefined When Called Using .call() Method
Arrow functions don't bind to this
as function
do. That's one of the main reason they were introduced (probably the most important one).
You cannot even bind
them.
ECMAScript 6 arrow function that returns an object
You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:
p => ({ foo: 'bar' });
You don't need to wrap any other expression into parentheses:
p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;
and so on.
Reference: MDN - Returning object literals
Two return statements in one arrow function
Actullay you are raising a concern about two approaches:
A.
if (condition) {
// do
// things...
}
B.
if (!condition) { return; }
// do
// things...
The rule is simple : If the function returns, it ignores every subsequent instruction.
And the answer is that they are equally efficient, but B is usually adopted to give better readability, especially when used to avoid many nested conditions.
Related Topics
Why Does a Regexp With Global Flag Give Wrong Results
$(Document).Ready Equivalent Without Jquery
How to Pad a Value With Leading Zeros
Difference Between == and === in JavaScript
How to Append Something to an Array
What Is the Temporal Dead Zone
What's the Difference Between '$(This)' and 'This'
Pass Correct "This" Context to Settimeout Callback
Get Selected Text from a Drop-Down List (Select Box) Using Jquery
How Does JavaScript Handle Ajax Responses in the Background
Parsing a String to a Date in JavaScript
How to Add a Delay in a JavaScript Loop
Short Circuit Array.Foreach Like Calling Break
Calculate Text Width With JavaScript
How to Send a Cross-Domain Post Request Via JavaScript
How Does the "This" Keyword in JavaScript Act Within an Object Literal