0

What is the proper way to declare a JavaScript 2d array? I've tried doing this

var matrix = new Array(new Array(2), new Array(2));   

but it doesn't want to work. I am complete javascript beginner so if you can please help me out. Thanks in advance

Nikola S.
  • 93
  • 10
  • FWIW: You don't "declare" arrays, because JavaScript is an untyped language. You create them. JavaScript also doesn't have multi-dimensional arrays. Insted, it has arrays of arrays. What you've done is one valid way to create a 2x2 "multidimensional" array. But see the linked question's answers for details. – T.J. Crowder Jan 14 '18 at 18:04

1 Answers1

0

There's no built-in way to do so, but it can be easily achieved in one line:

const rows = 5;
const cols = 3;
const defaultValue = 0;
Array(rows).fill(null).map(_ => Array(cols).fill(defaultValue));
Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141