Returns the last element of the indexed array if the array is not empty. If the target array is empty,
- An
UnexpectedEventError
will be thrown if the second parameter is specified with the value{ mustThrowErrorIfArrayIsEmpty: true }
. Additionally, TypeScript will infer that if the function executes without errors and the type of the array element is annotated (explicitly or implicitly) as neitherundefined
nornull
, the returned value could not beundefined
ornull
. null
will be returned if the second parameter has not been specified. If TypeScript is configured strictly, a non-null check will be required before using the returned value as non-nullable.
This function is not just an alternative to expressions like
targetArray[targetArray.length - 1]
; it also guarantees
that the last element of the array exists.
Examples
const sample: Array<string> = [ "alpha", "bravo", "charlie" ];
const lastElementOfSample: string | null = getLastElementOfArray(sample);
lastElementOfSample
holds the
value "charlie"
.
In this synthetic example, we assume knowledge of all elements of the sample
array in advance, which may not be practical, hence the nullable return
value.
console.log(lastElementOfSample.length);
length
property is applicable to strings (and arrays), while the
lastElementOfSample
constant may be
null
.
Before calling string properties and methods,
including length
, it is required to prove to
TypeScript that the value of lastElementOfSample
is not null
.
One way to do this is with a condition statement like
if (lastElementOfSample !== null) {/* ... */}
.
Inside the if-block, TypeScript
will recognize that this
value is not null
.
Other solutions exist, but using expressions like
lastElementOfSample!.length
is discouraged, as it
compromises code quality.
Such usage is often associated with employing the any
type and other
practices that negate the benefits of using TypeScript.
const notNullLastElementOfSample: string = getLastElementOfArray(sample, { mustThrowErrorIfArrayIsEmpty: true });
notNullLastElementOfSample
as
string
, not as
string | null
, because instead of returning
null
, the UnexpectedEventError
will be
thrown when the array is empty.
While you can handle this exception with try/catch
, there is
generally no advantage to doing this over the aforementioned
non-null check.
Quick Input in IntelliJ IDEA Family of IDEs
Using the functionality of Live templates in the IntelliJ IDEA family if IDEs allows you to quickly input code such as a function invocation expression. To get the Live templates of the YDEE library, you need to install the official plugin of this library.
Steps for Using the Live Templates
If you have not used Live templates before, do not worry if the instructions below are too complicated. Once you have developed the habit of using Live templates (similar to the habit of using keyboard shortcuts), the following operations will take a matter of seconds.
- Copy the variable name containing the array or array expression to the clipboard. To make it possible for the IDE to fill in the correct value for the parameter, please develop the habit of copying each time before inputting the Live template of the getLastElementOfArray function.
- Begin to input the function name (getLastElementOfArray).
There will be 2 options for autocomplete:
- Circled icon with the letter: it is the autocompletion of the function name, which is the standard functionality of the IDE. If you press the Enter key, the full function name will be inputted and also the function import declaration will be inserted if required. Not bad, but better automation is possible.
- The icon with the cliche is the template we need. Press Enter again. The code template will be inserted, with the value of the first parameter filled with the clipboard content and selected by the cursor. If you follow this procedure, there is no need to edit the inserted value; exit the parameter editing mode by pressing Enter again.
- Delete the unnecessary code.
You can use the alias of this Live Template — gleoa, which consists
of the first letters of all words in the function name.
However, the disadvantage of such aliases is that they are harder to memorize.
To get the autocomplete for getLastElementOfArray
, it is enough to remember the
first letters of the function name.