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
This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 1 year ago.
When I log this to the console it shows up as undefined. However, when I remove the braces in the function it logs the desired result. I'm confused -- aren't we always supposed to include curly braces in a function? Thank you all.
const shoutGreetings = arr => {
arr.map(word => word.toUpperCase() + '!')
};
const greetings = ['hello', 'hi', 'heya', 'oi', 'hey', 'yo'];
console.log(shoutGreetings(greetings))
Return the result of your map function:
return arr.map(...
This question already has answers here:
Curly Brackets in Arrow Functions
(3 answers)
Closed 1 year ago.
I encountered an issue while working on a project and I noticed that it was as a result of the curly braces in my function... quick example
const array1 = [1,2,3,4,5,6];
const array2 = [2,4,6];
const isPresentInBothArrays1 = array2.every((number)=>{
array1.includes(number);
});
console.log(isPresentInBothArrays1) //prints false;
const isPresentInBothArrays2 = array2.every((number)=>array1.includes(number));
console.log(isPresentInBothArrays2) //prints true;
why does isPresentInBothArrays1 with curly braces return false and IsPresentInBothArrays2 without curly braces return true?
It's because of the arrow function syntax, If you write something like this:
(param1, param2) => {//some expression}
is equivalent to this:
function f(param1, param2) {
// some expression
}
and because it does not have an explicit return statement it will return undefined by default.
However, if you omit the curly brackets and put a single expression that would be a shortcut and will return the value of that expression as the return value of the function.
So as for your question in the first form, it will return undefined from the function which evaluates to false and is not what you desire, but the second form correctly returns a boolean indicating the existence of the value.
you need to add return if you use curly braces:
const array1 = [1,2,3,4,5,6];
const array2 = [2,4,6];
const isPresentInBothArrays1 = array2.every((number)=>{
return array1.includes(number);
});
console.log(isPresentInBothArrays1) //prints true;
const isPresentInBothArrays2 = array2.every((number)=>array1.includes(number));
console.log(isPresentInBothArrays2) //prints true;
If you omit curly braces, arrow function will implicitly return the result of the expression after the =>.
However, if you use curly braces, you'll need to write return in order to make it return something, otherwise, it will return undefined.
So, in this particular case, you'll need to write:
const isPresentInBothArrays1 = array2.every(number => {
return array1.includes(number);
});
In case you want to have curly brackets for whatever reason.
This question already has answers here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
What does this symbol mean in JavaScript?
(1 answer)
Closed 2 years ago.
I am new to React. Recently I came across an application wherein some function had the definition as:
async function (a, b) => {//body} which is quite understandable. But also in the same apllication some functions had the structure as async function ({a,b}) => {//body}. What is the difference between defining function between the above two methods?
The second example is destructuring the function arguments. It basically provides a shorter syntax for extracting an object key's value without the dot notation mess
Let's say you have an object
const myObject = { x: 1, y: 2 };
So, when you pass myObject to the function, you can call the variables without the dot notation. This makes the code easier to read.
function myFunction({ x, y }) {
//Here you can use directly x instead of myObject.x
}
You can read more about destructuring here
in the first function your parameter are 2 different variables
, in the second function they are parameters of the object you are passing
like
let Cat = {
name:"catty",
color:"gray"
}
secound example you pass the whole object like this
function ( Cat ) {}
function ( { name , color } ) {
/// here you can use name and color as "catty" and "gray"
}
if you use the first expample you would have to specify the parameters like this
function (Cat.name , Cat.color) {
}
the word async refers to waiting this function to call
In the first case, there are 2 arguments passed into the function, in the second the first argument passed into the function is an object which is being destructured.
const obj = { a: 1, b: 2 }
async function foo({ a, b }) => {
a; // 1
b; // 2
}
foo(obj);
This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Arrow function without curly braces
(9 answers)
Closed 2 years ago.
Imagine I have an array containing movie objects such that
const movies: Movie[] = [ movie1, movie2, movie3, movie4 ];
I want to select a movie, for instance I have chosen movie2, then I want movie2 to be removed.
The following code works, Imagine m is the selected movie:
movies = movies.filter( m => m !== movie );
I want to understand how the arrow function works and tried the following code but it did not work.
movies = movies.filter( m => {
m !== movie;
});
What is the difference between those two codes?
The difference is, that the short-hand version implicitly returns the result. The long version from you is missing the return statements, like:
movies = movies.filter( m => {
return m !== movie;
});
This question already has answers here:
Arrow function without curly braces
(9 answers)
Closed 4 years ago.
We create presentational component or stateless component like this
const MyComponent = () => {
return(<div>my component</div>)
}
but I'd seen this
const MyComponent = () =>
<div>
<h1>head</h1>
my component
</div>
so now I'm confused when the braces is needed when using es6's arrow function.
This confused me on when rendering a list using map
shorter version
<div>
{map(o =>
<div>{o.name}</div>
)}
</div>
longer version
<div>
{map(o => {
return(<div>{o.name}</div>)
})}
</div>
Both are correct, but why write longer?
{map(o => // without curly brackets
<div>{o.name}</div> // this will be returned implicitly
)}
{map(o => { // with curly brackets
return <div>{o.name}</div> // you need to return explicitly
}
)}
If you do curly brackets ,
You have to explicilty return the data ,
When to use which one?
When you have mutliple line of execution you need to do curly brackets and return from it
But if you have single line of execution, that you need to return , then there is no need of curly brackets and return , it will return implicitly.
Same as If condition
if(true)
// do this for single line
else
// do this for single line
if() {
// do this for multiple line
} else {
// do this for multiple line
}
Arrow functions work both way to provide you with a bit of versatility. Say you need to perform some logic inside your function before you return, in this case you would need to add curly braces, i.e say you need to extract the name of a list of users, but you want to append their title.
let users = [new User(), ... ];
//...
let withTitle = users.map(p => {
const title = getTitle(p); // automagically returns Mr, Mrs, etc
return `${title} ${p.fullName}`
});
// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']
Now, you can declare a function that does the work for you, and use the shorthand version of the arrow function. like so.
const extractWithTitle: (user) => {
const title = getTitle(p); // automagically returns Mr, Mrs, etc
return `${title} ${p.fullName}`
}
let withTitle = users.map(p => extractWithTitle(p));
// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']
Now, an even shorter way to approach this would be to pass a reference to the function.
users.map(extractWithTitle);
Both are correct, but why write longer?
You basically need to use the longer version if you need to add more sentences in you arrow function other than the jsx component.
E.g.
<div>
{map(o => {
const name = "My name is: " + o.name;
return(<div>{name}</div>)
})}
</div>
Otherwise, you may use the short version.