Perform Matrix Addition in JavaScript

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

What you’ll learn

  • The rule Cij = Aij + Bij for matrices of the same size.
  • How to implement add and print helpers with nested for loops over rows and columns.
  • Two complete programs: a classic 3×3 demo and a smaller 2×2 variant, plus a browser live preview for the 3×3 sample and Try it editors (target="_blank").

Overview

Matrix addition is the entry-by-entry sum of two matrices of identical shape. In JavaScript you typically represent each matrix as an array of rows and fill the result with one nested loop nest.

Two programs

The reference 3×3 sample and a compact 2×2 illustration.

Live preview

Runs the same arithmetic as the first program on the built-in sample matrices.

Rigor

Shape rules, complexity, and realistic interview follow-ups in the FAQ.

Prerequisites

Arrays of arrays, nested loops, and printing with console.log.

  • Literals such as const M = [[1, 2], [3, 4]]; and zero-based indexing M[i][j].
  • array.join for spacing columns in simple console output.

What is matrix addition?

If A and B are both m × n matrices, their sum C is the m × n matrix with Cij = Aij + Bij for every valid row i and column j.

If the shapes differ, addition is not defined in ordinary linear algebra—your program should either require matching dimensions or report an error.

Same shape add entrywise
Different shape not defined

Formal definition

If A and B are both m × n matrices (same row and column counts), then C = A + B satisfies Cij = Aij + Bij for all valid i and j. The same entrywise rule applies to integer matrices.

2×2 example

[1 2; 3 4] + [4 3; 2 1] = [5 5; 5 5] — each position adds independently.

Intuition

Think of each cell as one independent slot: you never mix entries from different positions.

a11+b11 Top-left
Rule
Only a11 and b11 combine into c11.
m·n Adds
Work
An m × n sum needs m·n scalar additions.

Takeaway: nested loops simply schedule those m·n additions in row-major (or any fixed) order.

Live preview

Uses the same 3×3 integers as the first JavaScript program below. Press the button to print Matrix 1, Matrix 2, and the sum (text layout mirrors typical console output).

Matches the sample matrices in code example 1.

Live result
Press “Show 3×3 sum”.

Algorithm

Goal: given two matrices A and B of the same dimensions, produce C with C[i][j] = A[i][j] + B[i][j].

Confirm shape

Fixed literals already encode matching dimensions. For dynamic sizes, verify row and column counts (and rectangular rows) before adding.

Nested traversal

For each row index i and column index j, assign result[i][j] = mat1[i][j] + mat2[i][j].

Display (optional)

Print rows with spaces between entries and one console.log per row (or build strings with embedded newlines).

📜 Pseudocode

Pseudocode
function add_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

Add two 3×3 matrices (program with explanation)

Classic interview layout: addMatrices returns the sum; displayMatrix prints any supplied grid. Sample data matches the reference walkthrough.

JavaScript
function addMatrices(mat1, mat2) {
  const rows = mat1.length;
  const cols = mat1[0].length;
  const result = [];
  for (let i = 0; i < rows; i++) {
    result[i] = [];
    for (let j = 0; j < cols; j++) {
      result[i][j] = mat1[i][j] + mat2[i][j];
    }
  }
  return result;
}

function displayMatrix(matrix) {
  for (let i = 0; i < matrix.length; i++) {
    console.log(matrix[i].join(" ") + " ");
  }
}

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

const resultMatrix = addMatrices(matrix1, matrix2);

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

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

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

Explanation

The core is result[i][j] = mat1[i][j] + mat2[i][j] inside the nested loops. displayMatrix walks the same indices but logs each row as a string.

for (let i = 0; i < rows; i++) for (let j = 0; j < cols; j++)

Row-major visit. Each pair (i,j) is handled exactly once.

matrix[i].join(" ") + " "

Spacing. A trailing space after each row matches the classic printf-style layout.

2

Add two 2×2 matrices

Same pattern with smaller arrays: useful when an interviewer asks you to generalize dimensions verbally before fixing them at 3.

JavaScript
const ROWS = 2;
const COLS = 2;

function addMatrices(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 < m.length; i++) {
    console.log(m[i].join(" ") + " ");
  }
}

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

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

Explanation

ROWS and COLS make it obvious where to change sizes later; the arithmetic inside the loops is unchanged.

Optimization and extensions

Large matrices. For many entries (m · n large), memory bandwidth dominates; cache-friendly traversal (row-major for row-major storage) helps. Parallel workers can partition rows when correctness rules allow.

General size. Derive rows and cols from a.length and a[0].length, validate every row length, or use a flat buffer plus strides for dense numeric kernels.

Interview: start with the double loop and correct indexing; mention shape checks and complexity when asked.

❓ FAQ

They must have the same dimensions: the same number of rows and the same number of columns. Then each entry of the sum is the sum of the corresponding entries.
The usual interview approach is an array of row arrays, for example const A = [[1,2],[3,4]], i.e. row-major layout with A[i][j]. For numeric bulk work you might use TypedArray buffers with manual index i * COLS + j.
Yes: A + B = B + A entrywise. Associativity (A + B) + C = A + (B + C) holds as well.
Same shape requirement: C_ij = A_ij - B_ij. It is equivalent to adding A and (-B).
For an m×n matrix, adding two matrices touches each element once: O(m·n) time and O(1) extra space aside from storing the result.
You need to visit every row index i and column index j to compute result[i][j] = mat1[i][j] + mat2[i][j]. Two loops (outer rows, inner columns) match that traversal.

🔄 Input / output notes

The first program uses literal matrices. For interactive input you would read values (for example with prompt in the browser or readline in Node) into nested arrays before calling addMatrices, still checking that both inputs share the same dimensions and rectangular shape.

Edge cases and pitfalls

Most bugs are indexing and type issues, not the addition formula itself.

Shape

Mismatched dimensions

Never add A and B with different row or column counts. Validate sizes when building matrices from user input or APIs.

Overflow

Number safety

Summing two large entries can exceed Number.MAX_SAFE_INTEGER. Use BigInt or a wider numeric path if the problem allows huge entries.

Print

Row endings

Emit one line per row so output matches the usual rectangular layout.

⏱️ Time and space complexity

OperationTimeExtra space
Add two m × n matricesO(m · n)O(1) besides the output matrix
Print an m × n matrixO(m · n)O(1)

Summary

  • Definition: Cij = Aij + Bij for all positions; shapes must match.
  • Code: nested loops over rows and columns; optional helper to print rows.
  • Complexity: linear in the number of entries m · n.
Did you know?

Addition of real matrices is entrywise: (A+B)ij = Aij + Bij. It is only defined when A and B share the same shape (same row and column counts).

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