-1

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?

dasitha
  • 331
  • 2
  • 5
  • 15

2 Answers2

3

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

awarrier99
  • 3,628
  • 1
  • 12
  • 19
  • 1
    This question is asked a **lot**. There's a well-established [dupetarget](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value) for it. No need to post further answers. – T.J. Crowder May 14 '20 at 15:22
  • @T.J.Crowder I just started to learn arrow functions in JavaScript. – dasitha May 14 '20 at 15:27
  • @dasitha - The comment above isn't meant to criticize the question. It's to point out that posting an *answer* to it isn't how SO works. When there are already answers on SO, we point new questions at those, rather that cluttering up the site with 150 questions about the same thing with 300 different answers. – T.J. Crowder May 14 '20 at 15:28
1

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

Milenko
  • 529
  • 3
  • 5
  • This question is asked a **lot**. There's a well-established [dupetarget](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value) for it. No need to post further answers. – T.J. Crowder May 14 '20 at 15:22