Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

231
Vistas
Why am I getting an error with this multidimensional array?

I'm still new to Javascript and trying to understand multi-dimensional arrays. Why does the following code work?

var occupied = [[],[]];
occupied[1][0] = 0;
console.log(occupied[1][0]);

Yet, this code does not work.

var occupied = [[],[]];
occupied[2][0] = 0;
console.log(occupied[2][0]);

It also works with occupied[0][0]. Just not anything above 1.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

That's because you have defined only two items in your array (index 0 and index 1). So there is no index 2.

//      index:   0   1
var occupied = [ [], [] ];
occupied[1][0] = 0;
// works, index 1 exists
console.log(occupied[1][0]);
// error, index 2 doesn't exist
console.log(occupied[2][0]);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Size of your occupied array is 2 . So the maximum index you can access is 1. If you try to access any index above 1 it means that you are accessing undefined.

Now , as line 2 is, occupied[2][0] = 0 ; here occupied[2][0] is undefined and you cannot store anything inside undefined , which is causing you an error :)

about 4 years ago · Juan Pablo Isaza Denunciar

0

occupied[1][0] = 0; works because the length of occupied is 2. occupied[1] will access the second node, which is an empty array occupied[1][0] = 0; this will assign 0 to the first element of the second node of occupied array.

var occupied = [
  [], // Index 0
  [], // Index 1 => occupied[1][0] will access the first item of empty array in this location
];
occupied[1][0] = 0;
console.log(occupied[1][0]);
console.log(occupied);

occupied[2][0] = 0; this will not work. works because the length of occupied is 2. occupied[2] will try to access the third node occupied array, which donot exist. In this case occupied[2] is undefined. occupied[2][0] = 0; will try to set 0 to zeroth index of an undefined variable, this will throw a refrence errror like

Uncaught TypeError: Cannot set properties of undefined (setting '0')
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda