JavaScript Sliding Window

Beginner
6 min read
Updated: Nov 2026
3 examples

Definition and Usage

A sliding window moves a fixed-size view across a list so neighboring items can be compared or averaged together.

JavaScript Syntax

JavaScript
function windows(list, size) {
  const out = [];
  for (let i = 0; i <= list.length - size; i++) {
    out.push(list.slice(i, i + size));
  }
  return out;
}

console.log(JSON.stringify(windows([1, 2, 3, 4], 2)));
Try it Editor

How It Works

  1. Choose size. Here each window holds 2 items.
  2. Slide by one. Each step overlaps the previous window.
  3. Collect slices. Every position becomes a small array.

Examples

Example 1 — Day-over-Day Change

Compare each pair of consecutive numbers.

JavaScript
const days = [10, 12, 11, 15];
const changes = [];
for (let i = 0; i < days.length - 1; i++) {
  changes.push(days[i + 1] - days[i]);
}
console.log(changes.join(", "));
Try it Editor

How It Works

  1. Pairs. Each index with the next forms a window of 2.
  2. Subtract. Positive means an increase.

Example 2 — Moving Average

Average every three consecutive values.

JavaScript
const vals = [2, 4, 6, 8];
const avgs = [];
for (let i = 0; i <= vals.length - 3; i++) {
  const slice = vals.slice(i, i + 3);
  const avg = slice.reduce((a, b) => a + b, 0) / 3;
  avgs.push(avg);
}
console.log(avgs.join(", "));
Try it Editor

How It Works

  1. Window of 3. First window is 2+4+6.
  2. Slide. Next window is 4+6+8.

Example 3 — Same Idea as R.aperture

Ramda’s aperture builds these windows for you.

JavaScript
// Conceptual twin of R.aperture(2, list)
const list = ["a", "b", "c"];
const pairs = [];
for (let i = 0; i < list.length - 1; i++) {
  pairs.push(list[i] + list[i + 1]);
}
console.log(pairs.join(", "));
Try it Editor

How It Works

  1. Overlap. Each letter (except ends) appears in two pairs.
  2. Join. Concatenation shows the pair content.

Frequently Asked Questions

A fixed-length subarray that advances across a list, usually one step at a time.

Neighbor comparisons, streaks, moving averages, and pairwise transforms.

R.aperture(n, list) returns every overlapping window of length n.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful