简体   繁体   中英

Using arrow function in javascript to return the initials of the First Name and Last Name

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

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

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

Get first chars from names.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM