Construct an identity matrix of order n in JavaScript

An identity matrix is a square matrix where all diagonal elements are 1 and all other elements are 0. This type of matrix is fundamental in linear algebra and has the property that when multiplied with any matrix, it returns the original matrix unchanged.

What is an Identity Matrix?

An identity matrix of order n is an n × n square matrix where:

  • All diagonal elements (where row index equals column index) are 1
  • All other elements are 0

For example, an identity matrix of order 3 will be:

[
  [1, 0, 0],
  [0, 1, 0],
  [0, 0, 1]
]

Implementation

Here's a JavaScript function that constructs an identity matrix of order n:

const constructIdentity = (num = 1) => {
    const res = [];
    
    for (let i = 0; i < num; i++) {
        if (!res[i]) {
            res[i] = [];
        }
        
        for (let j = 0; j < num; j++) {
            if (i === j) {
                res[i][j] = 1;
            } else {
                res[i][j] = 0;
            }
        }
    }
    
    return res;
};

// Test with different matrix sizes
console.log("Identity matrix of order 3:");
console.log(constructIdentity(3));

console.log("\nIdentity matrix of order 5:");
console.log(constructIdentity(5));
Identity matrix of order 3:
[
  [ 1, 0, 0 ],
  [ 0, 1, 0 ],
  [ 0, 0, 1 ]
]

Identity matrix of order 5:
[
  [ 1, 0, 0, 0, 0 ],
  [ 0, 1, 0, 0, 0 ],
  [ 0, 0, 1, 0, 0 ],
  [ 0, 0, 0, 1, 0 ],
  [ 0, 0, 0, 0, 1 ]
]

Alternative Implementation

Here's a more concise version using Array.from() and ternary operator:

const constructIdentityMatrix = (n) => {
    return Array.from({ length: n }, (_, i) =>
        Array.from({ length: n }, (_, j) => i === j ? 1 : 0)
    );
};

console.log("Identity matrix of order 4:");
console.log(constructIdentityMatrix(4));
Identity matrix of order 4:
[
  [ 1, 0, 0, 0 ],
  [ 0, 1, 0, 0 ],
  [ 0, 0, 1, 0 ],
  [ 0, 0, 0, 1 ]
]

How It Works

The algorithm works by:

  1. Creating an empty array to store the matrix
  2. Using nested loops to iterate through each position (i, j)
  3. Setting the value to 1 when i equals j (diagonal elements)
  4. Setting the value to 0 for all other positions

Conclusion

Constructing an identity matrix in JavaScript is straightforward using nested loops. The key concept is setting diagonal elements to 1 and all others to 0, making it useful for various mathematical operations and linear algebra computations.

Updated on: 2026-03-15T23:19:00+05:30

984 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements