- Rule
- Only
a11andb11combine intoc11.
Perform Matrix Addition in JavaScript
What you’ll learn
- The rule Cij = Aij + Bij for matrices of the same size.
- How to implement add and print helpers with nested
forloops 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 indexingM[i][j]. array.joinfor 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.
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.
[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.
- Work
- An
m × nsum needsm·nscalar 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).
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
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]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.
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);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.
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.
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);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
🔄 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.
Mismatched dimensions
Never add A and B with different row or column counts. Validate sizes when building matrices from user input or APIs.
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.
Row endings
Emit one line per row so output matches the usual rectangular layout.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
Add two m × n matrices | O(m · n) | O(1) besides the output matrix |
Print an m × n matrix | O(m · n) | O(1) |
Summary
- Definition:
Cij = Aij + Bijfor 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.
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).
8 people found this page helpful
