From 7e286fdbb679a419f03e668506bf9ee8f5ff6c75 Mon Sep 17 00:00:00 2001
From: GAUTAM PALADIYA <47667794+gautam-paladiya@users.noreply.github.com>
Date: Wed, 19 Feb 2025 15:33:11 +0100
Subject: [PATCH] adding validation for peek and returning last element from
 array without calculating length

---
 .../stack/1.stack_with_array/stack_with_array.js            | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/javascript/datastructures/stack/1.stack_with_array/stack_with_array.js b/src/javascript/datastructures/stack/1.stack_with_array/stack_with_array.js
index 79ca3c5..95c0b78 100644
--- a/src/javascript/datastructures/stack/1.stack_with_array/stack_with_array.js
+++ b/src/javascript/datastructures/stack/1.stack_with_array/stack_with_array.js
@@ -21,7 +21,11 @@ class MyStack {
     }
 
     peek() {
-        return this.array[this.array.length - 1]; // return top most element from the stack without removing the element
+        // Underflow if stack is empty
+        if (this.isEmpty()) {
+            return "Underflow";
+        }
+        return this.array.at(-1); // return top most element from the stack without removing the element
     }
 
     // List of helper functions