Perform Matrix Multiplication in JavaScript

Beginner
⏱️ 12 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Linear algebra

What you’ll learn

  • The row × column rule: each entry of AB is a dot product of a row of A with a column of B.
  • Why three nested loops appear, and why the result buffer must start at zero before accumulating sums.
  • A full 3×3 program matching the classic output, a compact 2×2 second example, a live preview for the 3×3 case, and Try it (target="_blank").

Overview

Unlike addition, matrix multiplication combines whole rows with whole columns. The middle dimension must line up: columns of the left factor equal rows of the right factor.

Two programs

3×3 reference matrices and a smaller 2×2 product you can trace by hand.

Live preview

Browser math for the same 3×3 inputs as example 1.

Rigor

Dimension rules, complexity, and contrast with element-wise multiply in the FAQ.

Prerequisites

Nested loops and arrays of arrays; comfort with summing products in inner loops.

  • console.log, literal matrices such as [[1, 2], [3, 4]], and fixed N for square demos.
  • You already know matrix addition (same shape, add cells). Multiplication follows different rules.

What is matrix multiplication?

If A is m × n and B is n × p, then C = AB is m × p. Entry Cij is the sum, over k from 1 to n, of AikBkj.

In code with zero-based indices: C[i][j] collects sum_k A[i][k] * B[k][j].

Sizes (m×n)(n×p)→m×p
Not element-wise *

Formula

For compatible matrices, Cij = ∑k AikBkj. Each output cell is one dot product: row i of A dotted with column j of B.

Square case n × n

Both factors are n × n, so the product is n × n. The reference programs use n = 3 (and n = 2 in the second example).

Trace one cell

For the 3×3 sample, the top-left result entry uses row 0 of the first matrix and column 0 of the second: 1·9 + 2·6 + 3·3 = 30.

Row · Col Sum of products
k loop
Walks the shared dimension and accumulates into result[i][j].

Takeaway: the inner index k is where the first matrix’s column index meets the second matrix’s row index.

Live preview

Uses the same 3×3 integer matrices as example 1. Press the button to print both factors and AB.

Integer arithmetic in JavaScript; matches the classic sample.

Live result
Press “Show 3×3 product”.

Algorithm

Goal: compute C = AB for compatible square matrices of fixed size (here n × n).

Zero the output

Set every result[i][j] to 0 because you will accumulate sums with +=.

Triple loop

For each i and j, add A[i][k]*B[k][j] for all k in the shared dimension.

Print

Display A, B, and C with row-wise console.log loops.

📜 Pseudocode

Pseudocode
function multiply(A, B, C, n):   // n×n matrices
    for i from 0 to n - 1:
        for j from 0 to n - 1:
            C[i][j] ← 0
            for k from 0 to n - 1:
                C[i][j] ← C[i][j] + A[i][k] * B[k][j]
1

Multiply two 3×3 matrices

Same matrices and output pattern as the reference: multiplyMatrices fills result, displayMatrix prints with tabs.

JavaScript
const N = 3;

function multiplyMatrices(a, b) {
  const result = [];
  let i, j, k;

  for (i = 0; i < N; i++) {
    result[i] = [];
    for (j = 0; j < N; j++) {
      result[i][j] = 0;
    }
  }

  for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
      for (k = 0; k < N; k++) {
        result[i][j] += a[i][k] * b[k][j];
      }
    }
  }
  return result;
}

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

const firstMatrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const secondMatrix = [
  [9, 8, 7],
  [6, 5, 4],
  [3, 2, 1],
];

const result = multiplyMatrices(firstMatrix, secondMatrix);

console.log("First Matrix:");
displayMatrix(firstMatrix);

console.log("");
console.log("Second Matrix:");
displayMatrix(secondMatrix);

console.log("");
console.log("Result Matrix:");
displayMatrix(result);
Try it Yourself

Explanation

The innermost index k pairs a[i][k] with b[k][j]. Initializing result to zero matters because each result[i][j] is a sum of products.

result[i][j] += a[i][k] * b[k][j];

Accumulate. One product per k; repeat for all k to finish cell (i,j).

2

Smaller 2×2 product (easy to check by hand)

Same triple-loop pattern with N = 2. Top-left output is 1·5 + 2·7 = 19, and so on.

JavaScript
const N = 2;

function multiplyMatrices(a, b) {
  const result = [];
  for (let i = 0; i < N; i++) {
    result[i] = [];
    for (let j = 0; j < N; j++) {
      result[i][j] = 0;
      for (let k = 0; k < N; k++) {
        result[i][j] += a[i][k] * b[k][j];
      }
    }
  }
  return result;
}

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

const a = [
  [1, 2],
  [3, 4],
];
const b = [
  [5, 6],
  [7, 8],
];

const r = multiplyMatrices(a, b);

displayMatrix("A", a);
console.log("");
displayMatrix("B", b);
console.log("");
displayMatrix("AB", r);
Try it Yourself

Explanation

Combining zero-init with the k loop in one nest is a compact variant; mathematically it matches example 1.

Notes for larger problems

Non-square factors. Generalize loop bounds: i < rowsA, j < colsB, k < colsA (must equal rowsB).

Speed. Researchers use blocked (tile) multiplication and SIMD for huge matrices; interviews usually focus on correct triple loops first.

❓ FAQ

The number of columns of A must equal the number of rows of B. If A is m×n and B is n×p, the product AB exists and is m×p. If those inner sizes differ, multiplication is not defined this way.
No. Element-wise multiplication (Hadamard product) only works for same-shaped matrices and multiplies matching entries. Standard matrix multiplication uses the row-column dot-product rule shown on this page.
Typical order: i loops rows of the result, j loops columns of the result, k walks along the shared dimension to accumulate sum_k A[i][k]*B[k][j]. Some codes reorder loops for cache performance, but the math is the same.
Because each result entry is built as a running sum: result[i][j] += ... You must start from zero before adding products.
Products and sums can exceed Number.MAX_SAFE_INTEGER for large entries or sizes. Use BigInt matrices or floating-point paths when the problem demands it.
The classic triple loop does Θ(n³) arithmetic operations for square n×n matrices. Space aside from inputs/output is O(1) extra if you only store a few loop variables.

🔄 Input / output

Examples use literals in code. To accept typed input, read values into nested arrays (for example with prompt in the browser or readline in Node) and verify dimensions before multiplying.

Edge cases

Rules that trip beginners:

Shape

Inner dimensions

You cannot multiply m×n by p×q unless n = p.

Order

AB vs BA

Matrix multiplication is not commutative in general: AB and BA can differ.

Overflow

Integer products

Intermediate products may exceed safe integer range; consider BigInt or floating-point when inputs grow.

⏱️ Time and space complexity

SettingTimeExtra space
Two n × n matrices, classic triple loopO(n3)O(1) beyond outputs
m×n by n×pO(m · n · p)O(1) beyond outputs

Summary

  • Rule: Cij = sumk AikBkj; inner sizes of A and B must match.
  • Code: zero result, then three nested loops with += a[i][k]*b[k][j].
  • Complexity: cubic in n for square n×n matrices.
Did you know?

Matrix multiplication links rows of A with columns of B. You need A to be m × n and B to be n × p—the two n’s must match—then AB is m × p.

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