How to retrieve the last character of a string using Array.from() method in JavaScript

← Prev

The Array.from() method in JavaScript creates a new array from an array like object or an iterable. Its a very useful method. I'll show you how you can use the "Array.from()" method to retrieve the last character of a given string.

Array.from() Syntax

See the syntax first.

Array.from(arrayLike, mapFn, thisArg)

arrayLike: The "array like" or an iterable object (it can be a string) to convert into an array.

mapFn: A mapping function to call on every element of the array. This is optional.

thisArg: A value to use as "this" when calling the mapping function.



Feature Array.from()
Its purpose It converts an "array like" object or an "iterable" (such as Map()) into an array.
Return Type It returns a new array.
How to use? Array.from(arrayLike, mapFn, thisArg)
Example Array.from('Arun Banik') // Output: A,r,u,n, ,B,a,n,i,k

Example:

Now lets see how we can use "Array.from()" to get (or retrieve) the last character from a string.

<script>
  const str = 'Arun Banik';
  document.write(Array.from(str)[str.length -1]);   // Output: k
</script>
Try it

1) The Array.from() method in the above example, first converts the string into an array of characters. For example,

<script>
  const str = 'Arun Banik';
  document.write(Array.from(str));   // Output: A,r,u,n, ,B,a,n,i,k
</script>

2) The [str.length -1] returns the length of the string minus 1. This is used to calculate the index of the last character in the string. The output is "k".

💡 Alternatively, you can use the charAt() method to get a similar result. Check this out.

← Previous