You're getting confused with your various temporary arrays. The undefined values are caused by out-of-bounds access on the line below your innermost loop.

I recommend that you stick to making a single array for the result of the multiplication. As you're probably aware, the hitch is that JavaScript doesn't allow you to initialize a multi-dimensional array. To make a two-dimensional array, you have to initialize a one-dimensional array, then iterate over its elements and initialize each one to a one-dimensional array.

function multiply(a, b) {
  var aNumRows = a.length, aNumCols = a[0].length,
      bNumRows = b.length, bNumCols = b[0].length,
      m = new Array(aNumRows);  // initialize array of rows
  for (var r = 0; r < aNumRows; ++r) {
    m[r] = new Array(bNumCols); // initialize the current row
    for (var c = 0; c < bNumCols; ++c) {
      m[r][c] = 0;             // initialize the current cell
      for (var i = 0; i < aNumCols; ++i) {
        m[r][c] += a[r][i] * b[i][c];
      }
    }
  }
  return m;
}

function display(m) {
  for (var r = 0; r < m.length; ++r) {
    document.write('&nbsp;&nbsp;'+m[r].join(' ')+'<br />');
  }
}

var a = [[8, 3], [2, 4], [3, 6]],
    b = [[1, 2, 3], [4, 6, 8]];
document.write('matrix a:<br />');
display(a);
document.write('matrix b:<br />');
display(b);
document.write('a * b =<br />');
display(multiply(a, b));

Answer from Michael Laszlo on Stack Overflow
🌐
W3Schools
w3schools.com › ai › ai_matrices.asp
W3Schools.com
Using a JavaScript library will save you a lot of headache. One of the most common libraries to use for matrix operations is called math.js.
🌐
W3docs
w3docs.com › javascript
How to Create a Two Dimensional Array in JavaScript
The two-dimensional array is an array of arrays. Read this JavaScript tutorial and find out several methods of creating two dimensional arrays easily.
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-function-exercise-10.php
JavaScript function: Returns n rows by n columns identity matrix - w3resource
February 28, 2025 - For each column, it checks if the row index i is equal to the column index j. If i and j are equal, it pushes a 1 to the row array, otherwise it pushes a 0. After completing the row, it pushes the row array to the matrix array. Upon creating all rows and columns, the function returns the matrix array representing the identity matrix. ... See the Pen javascript-function-exercise-10-1 by w3resource (@w3resource) on CodePen.
🌐
W3Schools
w3schools.com › cssref › func_matrix.php
CSS matrix() function
CSS reference: CSS matrix3d() function. CSS tutorial: CSS 2D transforms. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › WebGL_API › Matrix_math_for_the_web
Matrix math for the web - Web APIs - MDN Web Docs
1 week ago - While this article uses CSS to ... matrices. These matrices consist of a set of 16 values arranged in a 4×4 grid. In JavaScript, it is easy to represent a matrix as an array....
🌐
Math.js
mathjs.org › docs › datatypes › matrices.html
math.js | an extensive math library for JavaScript and Node.js
The callback function of map and forEach has three parameters: value (the value of the currently iterated element), index (an array with the index value for each dimension), and matrix (the matrix being iterated). This syntax is similar to the map and forEach functions of native JavaScript Arrays, except that the index is no number but an Array with numbers for each dimension.
Top answer
1 of 14
23

You're getting confused with your various temporary arrays. The undefined values are caused by out-of-bounds access on the line below your innermost loop.

I recommend that you stick to making a single array for the result of the multiplication. As you're probably aware, the hitch is that JavaScript doesn't allow you to initialize a multi-dimensional array. To make a two-dimensional array, you have to initialize a one-dimensional array, then iterate over its elements and initialize each one to a one-dimensional array.

function multiply(a, b) {
  var aNumRows = a.length, aNumCols = a[0].length,
      bNumRows = b.length, bNumCols = b[0].length,
      m = new Array(aNumRows);  // initialize array of rows
  for (var r = 0; r < aNumRows; ++r) {
    m[r] = new Array(bNumCols); // initialize the current row
    for (var c = 0; c < bNumCols; ++c) {
      m[r][c] = 0;             // initialize the current cell
      for (var i = 0; i < aNumCols; ++i) {
        m[r][c] += a[r][i] * b[i][c];
      }
    }
  }
  return m;
}

function display(m) {
  for (var r = 0; r < m.length; ++r) {
    document.write('&nbsp;&nbsp;'+m[r].join(' ')+'<br />');
  }
}

var a = [[8, 3], [2, 4], [3, 6]],
    b = [[1, 2, 3], [4, 6, 8]];
document.write('matrix a:<br />');
display(a);
document.write('matrix b:<br />');
display(b);
document.write('a * b =<br />');
display(multiply(a, b));

2 of 14
20

You can use multiplyMatrices() function from: http://tech.pro/tutorial/1527/matrix-multiplication-in-functional-javascript it works like charm. Example (You can print a matrix with style in Chrome and Firefox console with console.table() ):

function multiplyMatrices(m1, m2) {
    var result = [];
    for (var i = 0; i < m1.length; i++) {
        result[i] = [];
        for (var j = 0; j < m2[0].length; j++) {
            var sum = 0;
            for (var k = 0; k < m1[0].length; k++) {
                sum += m1[i][k] * m2[k][j];
            }
            result[i][j] = sum;
        }
    }
    return result;
}

var m1 = [[1,2],[3,4]]
var m2 = [[5,6],[7,8]]

var mResult = multiplyMatrices(m1, m2)

/*In Google Chrome and Firefox you can do:*/

console.table(mResult) /* it shows the matrix in a table */

Find elsewhere
🌐
W3Schools
w3schools.com › js › js_arrays.asp
JavaScript Arrays
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
Robin Wieruch
robinwieruch.de › linear-algebra-matrix-javascript
Linear Algebra in JavaScript with Matrix Operations - Robin Wieruch
October 23, 2017 - How to use matrix operations from linear algebra in JavaScript. What are inverse, transpose and identity matrices and how can they help in machine learning ...
Top answer
1 of 16
122

Array.fill

Consider using fill:

Array(9).fill().map(()=>Array(9).fill())

The idea here is that fill() will fill out the items with undefined, which is enough to get map to work on them.

You could also fill directly:

Array(9).fill(Array(9))

(important note: Array(9).fill(Array(9)) will fill each row of the array with the same array, so changing one row will change the other rows).

Alternatives to Array(9).fill() include

Array(...Array(9))
[].push(...Array(9))
[].concat(Array(9))
Array.from(Array(9))

We can rewrite the solution a bit more semantically as:

function array9() { return Array(9).fill(); }
array9().map(array9)

or

function array(n) { return Array(n).fill(); }
array(9).map(() => array(9))

Array.from provides us with an optional second mapping argument, so we have the alternative of writing

Array.from(Array(9), () => Array.from(Array(9));

or, if you prefer

function array9(map) { return Array.from(Array(9), map); }
array9(array9);

For verbose description and examples, see Mozilla's Docs on Array.prototype.fill() here.
and for Array.from(), here.

Note that neither Array.prototype.fill() nor Array.from() has support in Internet Explorer. A polyfill for IE is available at the above MDN links.

Partitioning

partition(Array(81), 9)

if you have a partition utility handy. Here's a quick recursive one:

function partition(a, n) {
  return a.length ? [a.splice(0, n)].concat(partition(a, n)) : [];
}  

Looping

We can loop a bit more efficiently with

var a = [], b;
while (a.push(b = []) < 9) while (b.push(null) < 9);

Taking advantage of the fact that push returns the new array length.

2 of 16
95
var matrix = [];
for(var i=0; i<9; i++) {
    matrix[i] = new Array(9);
}

... or:

var matrix = [];
for(var i=0; i<9; i++) {
    matrix[i] = [];
    for(var j=0; j<9; j++) {
        matrix[i][j] = undefined;
    }
}
🌐
freeCodeCamp
freecodecamp.org › news › javascript-2d-arrays
JavaScript 2D Array – Two Dimensional Arrays in JS
November 7, 2024 - In this article, you will learn what two-dimensional arrays are and how they work in JavaScript.
🌐
Medium
rikyperdana.medium.com › multi-dimensional-matrix-in-functional-js-b2628df76d5e
Multi Dimensional Matrix in Functional JS | by Riky Perdana | Medium
April 9, 2024 - Multi Dimensional Matrix in Functional JS Matrix operations for aspiring mathematicians are pure cracks. Once you have a taste of this forbidden fruit, you’ll only crave for more. In the last …
🌐
W3Schools
w3schools.com › css › tryit.asp
W3Schools Tryit Editor - The matrix() Method
The W3Schools online code editor allows you to edit code and view the result in your browser
🌐
Medium
rikyperdana.medium.com › matrix-operations-in-functional-js-e3463f36b160
Matrix Operations in Functional JS | by Riky Perdana | Medium
April 26, 2024 - We make matrixMap to be a little more versatile than to just multiply the elements with certain number, but to alter the contents by any given expression.
🌐
Medium
dougschallmoser.medium.com › javascript-matrix-creation-3222c5113478
JavaScript Matrix Creation. I was recently working on a coding… | by Doug Schallmoser | Medium
February 24, 2021 - The Matrix is an oldie but goodie. Ultimately, what we need to create is an array of arrays, and then fill in each subarray with objects. Two arguments are provided when creating the grid: 1) rows — number of rows (each row is an array) 2) ...
🌐
Duke University
sites.math.duke.edu › ~jdr › linalg_js › doc › matrix.js.html
matrix.js
* * @desc * The arguments are {@link Vector} instances or Arrays of numbers, used as * the rows of the matrix. All rows must have the same length. * * @example {@lang javascript} * Matrix.create([1, 2], [3, 4], [5, 6]).toString(0); * // "[1 2] * // [3 4] * // [5 6]" * * @param {...(Array<number>|Vector)} rows - The rows of the matrix.
🌐
Programiz
programiz.com › javascript › multidimensional-array
JavaScript Multidimensional Array
In JavaScript, a multidimensional array contains another array inside it. In this tutorial, you will learn about JavaScript multidimensional arrays with the help of examples.
🌐
W3Schools
w3schools.com › jsref › jsref_obj_array.asp
JavaScript Array Reference
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.