Perform Matrix Subtraction in JavaScript

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Nested arrays

What you’ll learn

  • The element-wise rule Cij = Aij − Bij for matrices of the same size.
  • A complete 3×3 program (including negative differences), a compact 2×2 variant, a live preview, and Try it (target="_blank").
  • How subtraction relates to addition (A − B = A + (−B)) and common interview follow-ups.

Overview

Subtracting matrices works like subtracting numbers in a table: the top-left result uses the top-left of A minus the top-left of B, and so on for every cell.

Two programs

3×3 reference data and a 2×2 difference.

Live preview

Same integers as example 1; prints A, B, and A − B.

Negatives

Expect negative entries whenever B exceeds A in a cell.

Prerequisites

Same as matrix addition: nested loops and arrays of arrays.

  • console.log and row-major indexing mat[i][j]; literals like [[1, 2], [3, 4]].
  • JavaScript numbers can be negative; subtraction produces negatives naturally.

What is matrix subtraction?

For matrices A and B with the same shape, C = A − B is defined by Cij = Aij − Bij for every row i and column j.

Equivalently, subtracting B is adding (−B) entrywise.

Order A − B
Reverse B − A = −(A − B)

Live preview

Uses the same 3×3 inputs as example 1. Press the button to print Matrix 1, Matrix 2, and Matrix1 − Matrix2.

Matches the sample matrices in code example 1.

Live result
Press “Show 3×3 difference”.

Algorithm

Goal: compute C[i][j] = A[i][j] - B[i][j] for all cells.

Same shape

A and B must share row and column counts.

Subtract per cell

Nested loops over i and j; assign the difference to result[i][j].

Print

Optional helper to print each row with console.log.

📜 Pseudocode

Pseudocode
function subtract_matrices(A, B, C, rows, cols):
    for i from 0 to rows - 1:
        for j from 0 to cols - 1:
            C[i][j] ← A[i][j] − B[i][j]
1

Subtract two 3×3 matrices (program with explanation)

subtractMatrices computes matrix1 − matrix2. Values match the reference walkthrough (differences can be negative).

JavaScript
const N = 3;

function subtractMatrices(mat1, mat2) {
  const result = [];
  for (let i = 0; i < N; i++) {
    result[i] = [];
    for (let j = 0; j < N; j++) {
      result[i][j] = mat1[i][j] - mat2[i][j];
    }
  }
  return result;
}

function displayMatrix(matrix) {
  for (let i = 0; i < N; i++) {
    let line = "";
    for (let j = 0; j < N; j++) {
      line += matrix[i][j] + "\t";
    }
    console.log(line);
  }
}

const matrix1 = [
  [5, 8, 2],
  [7, 4, 9],
  [3, 6, 1],
];
const matrix2 = [
  [3, 1, 7],
  [6, 9, 2],
  [8, 5, 4],
];

const resultMatrix = subtractMatrices(matrix1, matrix2);

console.log("Matrix 1:");
displayMatrix(matrix1);

console.log("");
console.log("Matrix 2:");
displayMatrix(matrix2);

console.log("");
console.log("Resultant Matrix (Matrix1 - Matrix2):");
displayMatrix(resultMatrix);
Try it Yourself

Explanation

Each result[i][j] is one subtraction. Tab spacing keeps columns readable in the console.

2

Subtract two 2×2 matrices

Same pattern with ROWS / COLS; useful when an interviewer asks for a smaller trace-by-hand example.

JavaScript
const ROWS = 2;
const COLS = 2;

function subtractMatrices(a, b) {
  const out = [];
  for (let i = 0; i < ROWS; i++) {
    out[i] = [];
    for (let j = 0; j < COLS; j++) {
      out[i][j] = a[i][j] - b[i][j];
    }
  }
  return out;
}

function printMatrix(title, m) {
  console.log(title);
  for (let i = 0; i < ROWS; i++) {
    console.log(m[i].join(" ") + " ");
  }
}

const a = [
  [1, 2],
  [3, 4],
];
const b = [
  [4, 3],
  [2, 1],
];
const c = subtractMatrices(a, b);

printMatrix("A", a);
console.log("");
printMatrix("B", b);
console.log("");
printMatrix("A - B", c);
Try it Yourself

Explanation

Here 1 - 4 = -3 and 4 - 1 = 3 show negatives and positives in one small grid.

Notes

In place. You could write differences back into one array only if you no longer need the original operand stored there.

Unsigned bit tricks. Avoid treating differences as unsigned 32-bit values (>>> patterns): negatives become huge positives and hide bugs.

❓ FAQ

Subtraction works cell by cell like addition: same position in A minus same position in B. Matrix multiplication combines rows of A with columns of B and is a different operation entirely.
Yes. Each entry of A − B needs a matching entry in B, so both must be m×n for the same m and n.
Usually no. Subtraction is not commutative: B − A is the negative of A − B entrywise.
Yes. If A[i][j] &lt; B[i][j], the difference at that cell is negative. JavaScript numbers represent negatives naturally.
Subtracting two large integers can exceed Number.MAX_SAFE_INTEGER in edge cases. Use BigInt matrices if inputs can be huge.
Each of the m·n entries is computed once: O(m·n) time and O(1) extra space besides the output matrix.

🔄 Input / output

Programs above embed matrices in source. Interactive versions would read values into nested arrays (for example with prompt or readline) after checking dimensions.

Edge cases

Most issues match matrix addition: wrong sizes or numeric range.

Shape

Mismatched matrices

Subtraction needs identical dimensions, same as addition.

Range

Numeric overflow

Very large magnitudes can exceed safe integer range when subtracting; consider BigInt or floating-point.

⏱️ Time and space complexity

OperationTimeExtra space
Subtract two m × n matricesO(m · n)O(1) besides result storage

Summary

  • Definition: C = A − B with Cij = Aij − Bij; same shape required.
  • Code: nested loops; each cell is one subtraction.
  • Relation: A − B = A + (−B) entrywise.
Did you know?

Matrix subtraction is entrywise like addition: (A − B)ij = Aij − Bij. It is the same as adding A and (−B). The two matrices must have the same shape.

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.

8 people found this page helpful