Intermediate·Concept·2 min read

Stack and queue in JavaScript

Practice this question

Stack using array

JavaScript
const stack = [];
stack.push(1);
stack.push(2);
stack.pop();

Queue using array

JavaScript
const queue = [];
queue.push(1);
queue.push(2);
queue.shift();

Problems to practice

  • Valid Parentheses
  • Min Stack
  • Daily Temperatures
  • Sliding Window Maximum
  • Implement Queue Using Stack
  • Implement Stack Using Queue

Example: valid parentheses

JavaScript
function isValid(s) {
  const stack = [];
  const pairs = { ')': '(', ']': '[', '}': '{' };

  for (const ch of s) {
    if (['(', '[', '{'].includes(ch)) stack.push(ch);
    else {
      if (stack.pop() !== pairs[ch]) return false;
    }
  }

  return stack.length === 0;
}

Adapted from 16_DSA_JAVASCRIPT.md · “5. Stack and queue in JavaScript”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.