JavaScript Arrow Function throws Undefined [duplicate] - javascript

This question already has an answer here:
Why doesn't my arrow function return a value?
(1 answer)
Closed 2 years ago.
Below is my code for move all characters forward by one for a given string.
ex. abc => bcd
const moveCharForward = (str) => {
str
.split('')
.map(char => String.fromCharCode(char.charCodeAt(0) + 1)).join('');
}
console.log(moveCharForward('abcd'));
when I called the method it throws undefined.
I modified the code by removing the curly brackets like below.
const moveCharForward = (str) =>
str
.split('')
.map(char => String.fromCharCode(char.charCodeAt(0) + 1)).join('');
console.log(moveCharForward('abcd')); //working correctly
Now when I called the method its working correctly.
I want to know why throws undefined when Im adding method implemetation inside the curly brackets?

When using arrow functions like this, if you don't use curly braces, then JavaScript implicitly returns the value following the arrow. However, if you do use curly braces, then JavaScript expects a block of code, in which there must be a return statement in order to return a value

When you add the curly braces you need the return keyword. Without curly braces the return is implied

Related

Arrow function in Objects [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)
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed last month.
I've summerized my problem in an example below, the problems is, if I use in an object an arrow function with only one item (23) in the function (as below), I've to not to use curly brackets for it to work. Why is so? I thought it was optional not to use curly brackets when in the function there is only one item. Thanks
Doesn't work with curly brackets, returns undefined
obj = { y: () => {23} }
console.log(obj.y());
Works without curly brackets, returns 23
obj = { x: () => 23 }
console.log(obj.x());`
"to work with or without the curly brackets"

if statements in an arrow function [duplicate]

This question already has answers here:
How to use if-else condition in arrow function in JavaScript?
(6 answers)
Closed 4 years ago.
storyWords.filter(word => if (unnecessaryWords.includes(word)){
continue;
}
else{
betterWords.push(word);
}) ;
I keep getting an error "Unexpected token if", I was wondering if when you use an arrow function the syntax for if statements is different than in a regular function.
If you're having a statement (break, continue, if...else or switch) inside the arrow function you need to use curly braces: { }.
Arrow functions can have either a "concise body" or the usual "block body".
In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit return statement.
- MDN web docs
So write:
storyWords.filter(word => {
if (unnecessaryWords.includes(word)) {
continue;
} else {
betterWords.push(word);
}
});

Parsing the javascript reduce documentation [duplicate]

This question already has answers here:
What does this mean in documentation: square bracket followed by comma ( [, ) [duplicate]
(2 answers)
Closed 5 years ago.
In Mozilla's Reduce docs page I found the syntax below:
arr.reduce(callback[, initialValue])
The square brackets throw me off.
I have code like this that works:
const selectedItems = selectedItemsList.reduce((itemObject, item) => {
return {
...itemObject,
[item]: this.props.areasList.find(area => area.id === item)
};
}, {});
I do not use square brackets. I provide a callback and an initial value, separated by a comma. Can anyone elaborate on why the doc shows the syntax that it does for reduce? I only figured out the code in this post that I have by looking at other examples.
The square brackets mean that the initialValue parameter is optional, i.e. you don't have to provide it. You shouldn't actually place these brackets in your code.

arrow function shorthand for returning an object [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 6 years ago.
Im using the shortened ES6 arrow function notation to write my function body like this
const funcName = (...args) => something
I'm not even using a single curly bracket since my function body has just 1 return statement.
But say I want to return an object from this function, I would have to do:
const funcName = (...args) => {key:val}
The problem here is babel is assuming that the stuff inside the curly brackets is a function body - not an object - how to make it think that it is indeed an object??
Embrace it with brackets
const funcName = (...args) => ({key:val})

nodejs arrow function with expression [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 6 years ago.
According to the documentation, you can return an expression from an arrow function:
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }
but this doesn't seem to work as I would expect (nodejs 4.2.3)
> [1,2,3].map(i => i);
[ 1, 2, 3 ]
> [1,2,3].map(i => {});
[ undefined, undefined, undefined ]
Shouldn't the 2nd example return 3 empty objects? Or am I missing something?
According to the docs, the body of fat arrow function can be written as either a single expression or a series of statements wrapped into {} (just as you write bodies of plain old functions).
The point is, if parser encounters { after the =>, it goes with the second option. Now, it doesn't matter whether or not you use empty object literal or full object literal (like { a: 2 } in the first edit of this answer) - it's never treated as object literal, only as a function's body.
And what happens if function doesn't have a return statement? Right - this function returns undefined. That's why you get three of those as result of map (both for => {} and for => { a: 2 }).
To get three empty objects instead, just wrap {} into (), like this:
[1,2,3].map(i => ({}));
... as it forces the parser to go with expression path.

Categories

Resources