# JavaScript Exercises: Top and bottom elements of a stack

## JavaScript Stack: Exercise-10 with Solution

Write a JavaScript program to find the top and bottom elements of a given stack.

Sample Solution:

JavaScript Code:

``````class Stack {
constructor() {
this.items = [];
}

push(element) {
this.items.push(element);
}

pop() {
if (this.isEmpty())
return "Underflow";
return this.items.pop();
}

peek() {
if (this.isEmpty())
return "No elements in Stack";
return this.items[this.items.length - 1];
}

isEmpty() {
return this.items.length === 0;
}
get_Top() {
return this.items[this.items.length - 1];
}
get_Bottom() {
return this.items[0];
}
displayStack(stack) {
console.log("Stack elements are:");
let str = "";
for (let i = 0; i < stack.items.length; i++)
str += stack.items[i] + " ";
return str.trim();
}
}

console.log("Initialize a stack:")
let stack = new Stack();
console.log("Input some elements on the stack:")
stack.push(1);
stack.push(6);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(7);
console.log(stack.displayStack(stack));
console.log("Top element of the stack is:", stack.get_Top());
console.log("Bottom element of the stack is:", stack.get_Bottom());
```
```

Sample Output:

```"Initialize a stack:"
"Input some elements on the stack:"
"Stack elements are:"
"1 6 3 2 5 7"
"Top element of the stack is:"
7
"Bottom element of the stack is:"
1
```

Flowchart:

Live Demo:

* To run the code mouse over on Result panel and click on 'RERUN' button.*

Live Demo:

See the Pen javascript-common-editor by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Stack Previous: Remove duplicates from a given stack .
Stack Exercises Next: Rotate the stack elements to the left.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## JavaScript: Tips of the Day

Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function

Example:

```const tips_unzip = (arr, fn) =>
arr
.reduce(
(acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
Array.from({
length: Math.max(...arr.map(x => x.length))
}).map(x => [])
)
.map(val => fn(...val));

console.log(tips_unzip([[2, 15, 200], [3, 25, 300]], (...args) => args.reduce((acc, v) => acc + v, 0)));
```

Output:

```[5, 40, 500]
```