Emmanuel Akinfulubi

JavaScriptFunction

Create an identity matrix in JavaScript

Beginner · 4 min read

A matrix is a grid of numbers, stored in JavaScript as an array of rows, where each row is itself an array. The identity matrix is the simplest useful one: ones running diagonally from the top left to the bottom right, and zeros everywhere else. Graphics code, games and maths libraries use it as the "do nothing" starting point, the way 0 is for adding and 1 is for multiplying.

In this tutorial you will write identity(n), which builds the identity matrix of any size. You will also walk into a trap with fill that catches a lot of people, and learn how Array.from avoids it. You need to know what an array is and what an arrow function looks like.

What it looks like

Here is the 3 by 3 identity matrix, first as a grid, then as JavaScript:

Output

1 0 0
0 1 0
0 0 1

JavaScript

const grid = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
console.log(grid[1][1]); // 1
console.log(grid[1][2]); // 0

grid[1][2] means "row 1, then column 2", counting from 0. The rule for the whole matrix fits in one sentence: the value at row i, column j is 1 when i === j, and 0 otherwise.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

10 Build an identity matrix

easy

Return the n by n identity matrix: ones down the diagonal, zeros everywhere else.

Stuck? Three hints, smallest first
  1. 1. The value at row i, column j is 1 when i === j.
  2. 2. Array(n).fill(row) puts the same row object in every position.
  3. 3. Array.from({ length: n }, ...) calls the function once per row, giving distinct rows.

Step 1: the tempting shortcut

new Array(n) makes an array with n empty slots, and fill(value) puts the same value in every slot. So a first attempt builds one row of zeros and fills the matrix with it, then sets the diagonal:

Step 1

const broken = (n) => {
  const row = new Array(n).fill(0);
  const matrix = new Array(n).fill(row);
  return matrix.map((r, i) => { r[i] = 1; return r; });
};
console.log(broken(3)); // [ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ]

All ones. Something went badly wrong.

Step 2: why every row changed

An array is an object, and a variable holding an object holds a reference to it, like an address. fill(row) copied the address three times. It did not make three rows. All three positions point at the same array:

Step 2

const b = broken(3);
console.log(b[0] === b[1]); // true

So setting r[0] = 1 in the first row, r[1] = 1 in the second and r[2] = 1 in the third all changed that one shared row. That is why every "row" reads [1, 1, 1].

The same trap catches fill([]) and fill({}). Whenever you mean "n separate things", fill with an object gives you "one thing, n times".

Step 3: Array.from makes a fresh row each time

Array.from({ length: n }, fn) builds an array of length n and calls fn once for each position. The function receives two values: the current item (which we ignore, so we name it _) and its index:

Step 3

console.log(Array.from({ length: 4 }, (_, i) => i * 10)); // [ 0, 10, 20, 30 ]

Because fn runs again for every position, anything it creates is new each time. That is exactly what the rows need.

Step 4: build the rows and columns

Use Array.from twice: the outer one makes each row, the inner one makes each value in that row, using the i === j rule:

Step 4

const identity = (n) =>
  Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 1 : 0)));
console.log(identity(3)); // [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]
console.log(identity(1)); // [ [ 1 ] ]
console.log(identity(0)); // []

i is the row number and j is the column number. i === j ? 1 : 0 reads "if this is on the diagonal, 1, otherwise 0".

Step 5: check the rows are separate

Step 5

const m = identity(3);
console.log(m[0] === m[1]); // false
m[0][0] = 99;
console.log(m[1][1]); // 1
console.log(m[0]);    // [ 99, 0, 0 ]

Changing row 0 left row 1 alone. Each row is its own array.

Step 6: print it as a grid

The answer has a small helper to print the matrix the way you would draw it. r.join(' ') turns each row into text like 1 0 0, and joining the rows with '\n', a new line, stacks them:

Step 6

const show = (m) => m.map((r) => r.join(' ')).join('\n');
console.log(show(identity(2)));

That prints 1 0 on one line and 0 1 on the next.

The full solution

The panel has identity, the broken version and show. It prints the 3 by 3 matrix as a grid, the 1 by 1 and 0 by 0 cases, and then the broken version, so you can see the shared-row bug for yourself. Press Run to compare.

The answer

// Array.from calls the mapper per row, so each row is a separate array.
const identity = (n) =>
  Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 1 : 0)));

// The trap: fill puts the SAME array in every row.
const broken = (n) => {
  const row = new Array(n).fill(0);
  const matrix = new Array(n).fill(row);      // every row is the identical object
  return matrix.map((r, i) => { r[i] = 1; return r; });
};

const show = (m) => m.map((r) => r.join(' ')).join('\n');

console.log('identity(3):');
console.log(show(identity(3)));
console.log('identity(1):', JSON.stringify(identity(1)));
console.log('identity(0):', JSON.stringify(identity(0)));
console.log('--- the fill trap ---');
console.log('broken(3):');
console.log(show(broken(3)), '<- every row is the same array, so all diagonals got set');

const m = identity(3);
m[0][0] = 99;

Output


      
15 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 15 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

15 checks

test('a 3x3 identity', identity(3), [[1, 0, 0], [0, 1, 0], [0, 0, 1]]);
test('a 1x1 identity', identity(1), [[1]]);
test('a 0x0 identity is empty', identity(0), []);
test('a 4x4 has four rows', identity(4).length, 4);
test('each of four columns', identity(4).every((r) => r.length === 4), true);
test('the diagonal is all ones', identity(5).every((r, i) => r[i] === 1), true);
test('and everything else is zero', identity(5).every((r, i) => r.every((v, j) => (i === j ? v === 1 : v === 0))), true);
test('the total of every entry is n', identity(6).flat().reduce((a, b) => a + b, 0), 6);
test('the rows are distinct objects', identity(3)[0] === identity(3)[1], false);
test('so changing one row leaves the others alone', (() => { const x = identity(3); x[0][0] = 99; return x[1][1]; })(), 1);
test('and the change is visible in its own row', m[0], [99, 0, 0]);
test('while fill shares one row between all of them', (() => { const b = broken(3); return b[0] === b[1]; })(), true);
test('which corrupts the result', broken(3)[0], [1, 1, 1]);
test('so every row reads the same', (() => { const b = broken(3); return b[0] === b[2]; })(), true);
test('instead of the identity matrix', same(broken(3), identity(3)), false);

Array(n).fill(row) is the trap, and it is worth meeting once. fill stores the same reference in every position, so all n rows are one array wearing n hats — setting row[i] = 1 for each i sets every diagonal position on the single shared row, and the assertion shows [1, 1, 1] coming out.

Array.from({ length: n }, mapper) calls the mapper once per index, so each row is a fresh array. The assertion that identity(3)[0] !== identity(3)[1] is checking exactly that. The same trap catches fill({}), fill([]) and any new Array(n).fill(someObject) — anywhere you meant "n separate things" and got "one thing, n times".

Common mistakes

  • Filling with one row object. new Array(n).fill(row) puts the same array in every position, so one change shows up everywhere.
  • Swapping rows and columns. In m[i][j], i is the row and j is the column. For the identity matrix it makes no difference, but for other grids it does.
  • Calling map on new Array(n). The slots are empty, and map skips empty slots, so your function never runs. Array.from has no empty slots.

Try it yourself

  1. Write zeros(rows, cols) that returns a grid of zeros with separate rows. Check it with === as in Step 5.
  2. Build a matrix where every value is i + j. What pattern do you see on the diagonals?
  3. Add up every value in identity(6) with flat() and reduce. You should get 6.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.