A stack is a data structure that has way more limitations, compared to arrays. We can add items to a stack only by adding them on top. And we can only remove the item on top of the stack.
The order in which elements come off a stack gives rise to its alternative name, LIFO (last in, first out).
Implementing a Stack in JavaScript
const stack = [1,2,3,4];
stack.push(5);
// [1,2,3,4,5]
stack.pop();
// -> 5
// [1,2,3,4]
Example :
let letters = [];
let word = "racecar";
let reverseword = "";
// put letters of words in to stack
for (let i = 0; i < word.length; i++) {
letters.push(word[i]);
}
console.log(letters);
// pop off the stack in reverse order
for (let i = 0; i < word.length; i++) {
reverseword += letters.pop();
}
console.log(reverseword);
if (reverseword === word) {
console.log(word + "is a palindrome");
} else {
console.log(word + "is not a palindrome");
}
//output: racecar is a palindrome