This question already has answers here:
Arrow function without curly braces
(9 answers)
Curly Brackets in Arrow Functions
(3 answers)
Closed 4 years ago.
What's the difference between these two in javascript? what does it mean in scripting?
const Test1 = () => {
console.log('test1')
}
const Test2 = () => (
console.log('test2')
)
The "basic" form is with curly braces, just like regular functions:
() => {
...
}
However, arrow functions allow one special case shorthand:
() => plain expression
If you don't use curly braces, you may use one plain expression instead, with an implicit return. I.e. these two are equivalent:
() => { return 42; }
() => 42
So your version using parentheses counts as the single expression version and the return value of console.log will be returned (which is undefined either way though), whereas it won't on the version using curly braces.
Second example used to simplify returning of function, but in this case you can use only one expression, so you cannot write large of code. Try to run this example to better understand:
const Test1 = () => {
'test1'
}
console.log(Test1())
const Test2 = () => ( test = 'test4')
console.log(Test2())
Also this declaration method uses to simplify returning objects:
const Test3 = () => ({ a: 1, b: 2 });
console.log(Test3());
Related
I'm shortening a function expression to an arrow function expression.
When can I remove the curly brackets of the function? Can you always or is there a rule when you're allowed?
I see on (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) it says you can drop curly brackets when you use just a single expression:
However, I understood the following to be 2 expressions, and the absence of curly brackets doesn't stop the function from running. It does still create an implicit return and just returns the first expression. Is this all I need to know about getting rid of curly brackets in arrow function expressions?
f = () => x = 5 * 5; this;
console.log(f());
Check out this article on MDN on arrow functions MDN Arrow functions
What I believe you are talking about is an implicit return.
If you remove the curly braces from an arrow function it is implied that you will return what ever the code tells it to do
let implicitAddFunc = (arg) => arg + 2;
In this example you do not need to explicitly declare what you are returning from the function. When you are using curly braces you must actually call out what you are returning
let nonImplicitAddFunc = (arg) => {
let returnValue;
returnValue = arg + 2
//With curly brace must have the keyword *return*
return returnValue
}
For a deeper dive please reference this post When should I use `return` in es6 Arrow Functions?
On this example you need a square brackets because you need to do something in function body:
const data = {a: 1, b: 2};
const functionWithReturn = () => {
const newData = {
...data,
c: 3
}
return newData;
}
This is shortcut for return (which doing exactly the same as previous):
const functionShort = () => ({
...data,
c: 3
})
The only difference that on the first example you can do something else inside function (like calling another function, make some data mutation...).
This question already has answers here:
Curly Brackets in Arrow Functions
(3 answers)
Closed 2 years ago.
I have a .map() function that changes isActive property value of objects in data array. However wraps it with curly braces returns me undefined whereas wrapping it with parenthesis or no wrap returns the updated value. Curly braces are used as a wrapper in an arrow function but does it work differently for .map()?
const newData = data.map((data) => {
data.label === label ? { ...data, isActive: !data.isActive } : data,
});
console.log(newData)
//undefined
const newData = data.map((data) =>
data.label === label ? { ...data, isActive: !data.isActive } : data,
);
console.log(newData)
//returns updated newData
That’s the behavior of arrow function. Arrow function syntax is designed to be terse.
(arg) => [single expression]
If what follows the arrow is one single expression without curly braces, it implies returning the value of that expression. The return keyword is omitted.
If wrapping curly braces follows the arrow, then what goes inside the braces are treated as normal function body, and return keyword must be used if you mean to return a value.
So (x) => x + 1 is translated to:
function (x) {
return x + 1;
}
And (x) => { x + 1 } is translated to:
function (x) {
x + 1;
}
I must also add that (x) => ({ x }) is translated to:
function (x) {
return { x: x };
}
Curly brace {...} can mean an object literal, a function body or a code block.
In order to disambiguate, you need to put parenthesis around the braces to tell the parser to interpret {...} as an “object literal expression”.
This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
Its known that someone can make a one-line array function like this to return the single value:
var func = (x) => x + 1 //func(2) == 3
and you can also make multi-line array-functions, whose values need to be manually returned:
var funcMultiline = (x) => {
var result = 1;
result += x;
return result;
}
funcMultiline(4) == 5; //true
So the question:
let's say I want to return a new object in one line, if I use the brackets, then the array-function is treated like a multi-line function, and doesn't actually return the object-literal. Is there any direct way to create an object literal in, lets say, a map function? Like:
[...Array(25)].map(e => {x: 5, y:10}) //this is a syntax error, but how can I make this work
Returning object literals using the concise body syntax params => {object:literal} will not work as expected.
You have to wrap the object literal with parenthesis:
var res = [...Array(25)].map(e => ({x: 5, y:10}))
console.log(res);
This question already has an answer here:
Why doesn't my arrow function return a value?
(1 answer)
Closed 4 years ago.
So to my understanding which is obviously wrong at this moment in time is that,
return arg => arg*2
is the same as
return (arg)=>{arg*2}
I always assumed arrow functions are just syntactically neater.
But doing this with closures like so doesn't work.
function addTwoDigits(firstDigit){
return (secondDigit)=>{firstDigit + secondDigit}
}
let closure = addTwoDigits(5);
console.log(closure(5)) // Undefined
Yet this is fine
function addTwoDigitsV2(firstDigit){
return secondDigit => firstDigit + secondDigit
}
let closure2 = addTwoDigitsV2(10);
console.log(closure2(10))// 20
arrow function works differently here:-
(x)=> x*2 ; // dont have to return anything, x*2 will be returned
is not same as
(x) =>{x*2}
//here you need to return something otherwise undefined will be returned
When you use {} you must set return
return (arg)=>{return arg*2}
The arrow function only supplies the return automatically if you have an expression after the arrow. If the arrow is followed by a curly brace, it's treated as the braces around a function body, so you have to write return explicitly, i.e.
arg => arg * 2
is equivalent to:
(arg) => { return arg * 2; }
function addTwoDigits(firstDigit) {
return (secondDigit) => {
return firstDigit + secondDigit
}
}
let closure = addTwoDigits(5);
console.log(closure(5))
You need a return statement if the body of your arrow function is wrapped in { ... }.
Since yours is a single expression, you can skip the {-} and return. But if you have the {-}, you need the return statement.
The parentheses are not an issue here. You need them if you have more than a single parameter. With one, they're optional.
This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
What does the arrow function with a () after means? [duplicate]
(3 answers)
ES6 Fat Arrow and Parentheses `(...) => ({...})` [duplicate]
(2 answers)
What does arrow function '() => {}' mean in Javascript? [duplicate]
(2 answers)
Closed 5 years ago.
I've seen JavaScript code such as this:
let a = () => ({ id: 'abc', name: 'xyz' })
What do the parentheses ( … ) wrapping the object refer to in this instance? Is it a shorthand for return?
No. Those parentheses produce an object literal. Arrow functions have many syntaxes, one of which is:
( … ) => expression
This will implicitly return an expression, for example:
() => 1 + 1
This function will implicitly return 1 + 1, which is 2. Another one is this:
( … ) => { … }
This will create a block to house multiple statements if you don't want to implicitly return an expression, and if you want to do intermediate calculations or not return a value at all. For example:
() => {
const user = getUserFromDatabase();
console.log(user.firstName, user.lastName);
}
The problem arises when you want to implicitly return an object literal. You can't use ( … ) => { … } because it'll be interpreted as a block. The solution is to use parentheses.
The parentheses are there for the { … } to be interpreted an object literal, not a block. In the grouping operator, ( … ), only expressions can exist within them. Blocks are not expressions but object literals are, thus an object literal is assumed. Thus, instead of creating a block, it will use this syntax:
( … ) => expression
And implicitly return an object literal. Without the parentheses, it will be interpreted as labels and strings, not keys and values of an object literal.
let a = () => {
id: 'abc', //interpreted as label with string then comma operator
name: 'xyz' // interpreted as label (throws syntax error)
}
The comma here would be interpreted as the comma operator, and since the operands must be expressions, and labels are statements, it will throw a syntax error.
It allows you to create an expression, so
let a = () => ({ id: 'abc', name: 'xyz' })
specifies that a when invoked, returns the enclosed object
If you remove the () in this case, it will throw an error because it is not a valid function body statement, because the {} in let a = () => { id: 'abc', name: 'xyz' } are interpreted as the boundaries of a statement, but the content inside is not valid if you look at it.
let a = () => {
id: 'abc', /* Not valid JS syntax */
name: 'xyz'
}