Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Javascript code file #1379

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Data-Structures/Array/LastElementInArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* This function will accept an array and Return its last element
* @param {Array} arr array with elements of any data type
* @returns {*} The last element of the array.
* @complexity O(1) (Best case, Average case, worst case)
*/
const findLastElement = (arr) => {
// If arr is not an array or its length is zero then the function will throw Error
if (!Array.isArray(arr) || arr.length === 0) {
throw new Error("Input must be a non-empty array.");
}
// Calculate the length of the input array
const array_lenght = arr.length;
// Calculate the index of the last element of the array
const LastElementIndex = array_lenght - 1;
return arr[LastElementIndex];
}

export { findLastElement };
Loading