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"));

1

5 Answers 5

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"));

Sign up to request clarification or add additional context in comments.

1 Comment

(They're also looking for initials rather than entire strings)
1

Get first chars from names.

const getInitials = (firstName, lastName) => `${firstName[0]}${lastName[0]}`
console.log(getInitials("Charlie", "Brown"));

Comments

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"));

Comments

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"));

Comments

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

1 Comment

While this answer might solve the issue, please include some additional explanatory text to assist readers understand what it is doing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.