0

Trying to have console log show the initials of the first and last name when using arrow functions in javascript.

const getInitials = (firstName, lastName) => {
  firstName + lastName;
}
console.log(getInitials("Charlie", "Brown"));
Barmar
  • 741,623
  • 53
  • 500
  • 612
13arrz
  • 7
  • 1
  • Does this answer your question? [How to get first character of string?](https://stackoverflow.com/questions/3427132/how-to-get-first-character-of-string) – German Quinteros Feb 25 '20 at 05:07

5 Answers5

2

You have to specify return inside the curly brackets. You can use charAt() to get the initials:

const getInitials = (firstName,lastName) => { return firstName.charAt(0) + lastName.charAt(0); }
console.log(getInitials("Charlie", "Brown"));

OR: You do not need the return if remove the curly brackets:

const getInitials = (firstName,lastName) => firstName.charAt(0) + lastName.charAt(0);
console.log(getInitials("Charlie", "Brown"));
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

You're not returning the initials, you're returning the whole name. Use [0] to get the first character of a string.

In an arrow function, don't put the expression in {} if you just want to return it as a result.

const getInitials = (firstName, lastName) => firstName[0] + lastName[0];
console.log(getInitials("Charlie", "Brown"));
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Get first chars from names.

const getInitials = (firstName, lastName) => `${firstName[0]}${lastName[0]}`
console.log(getInitials("Charlie", "Brown"));
Siva K V
  • 10,561
  • 2
  • 16
  • 29
0

When you give an arrow function a code block ({}), you need to explicitly define the return statement. In your example, you don't need a code block since you're only wanting to return a single value. So, you can remove the code block, and instead place the return value to the right of the arrow =>.

In order to get the first characters in your strings, you can use bracket notation ([0]) to index the string, .charAt(0), or even destructuring like so:

const getInitials = ([f],[s]) => f + s;
console.log(getInitials("Charlie", "Brown"));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0
const getInitials = (firstName,lastName) => { return firstName.charAt(0) + lastName.charAt(0); }
console.log(getInitials("Charlie", "Brown"));
Kenyi Larcher
  • 282
  • 1
  • 8
  • 2
    While this answer might solve the issue, please include some additional explanatory text to assist readers understand what it is doing. – morgan121 Feb 25 '20 at 05:51