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

104
Vistas
Why does console.log display array different than alert?

I wrote a function that filters objects in a specific manner (grouped by key but only consecutive ones, it works fine).

groupBySequentialValues(array, key) {
    let groupName = null;
    let groupIndex = 0;
    let result = []; // keep this in mind!

    array.forEach((el, index) => {
        if (groupName !== array[index][key]) {
            groupName = array[index][key]
            groupIndex++;
            result[groupIndex + '_' + groupName] = []
        }
        result[groupIndex + '_' + groupName].push(el);
    })

    alert(result);
    console.log(result);
}

At first the alert shows an empty array, but after the alert is closed, the console log will show the correctly assembled array. (This also happends without the alert of course, this just shows the difference the best)
But I cannot use this array in alerts or in the template (I use it in VueJS to render a list, but its empty like I said).

Somehow dev tools seems to see its contents but alert/the dom doesnt.
After declaring the result array as an object ({} instead of []) it worked.

Why does dev tools/console log behave this way? Its a debug tool, but when it behaves like this I cannot rely on it as a debugging tool..

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

0

When constructing an object and printing that object to the console, console.log() will output the object's own properties and their values. If you console.log() the object using the object's .toString() method you will receive [object Object] in the console. This is the exact result you see in the alert of the object:

const obj = {};
obj['test'] = 'this is a test';
console.log(obj);
console.log(obj.toString());
alert(obj);

If you create an array and console.log() its internal toString() method prints the elements of the array comma separated with [] surrounding them. When alert()ing an array, the .toString() method is used to print only the array values:

let arr = [1,2,3];
console.log(arr);
alert(arr);

Finally, your code adds properties to an Array Object rather than adding elements to the array. When this occurs, console.log() prints this Object exactly like the first example, but because this is an Array Object, it places [] around the properties and their values rather than {}. Since the array is empty (no elements), it prints [] literally.

The code below demonstrates the structure of the Array Object your code creates, shows the number of array elements is zero, shows the Array Object's property names, shows the value associated with that property and finally shows the object in the console.

If you alert the result as explained in the previous example, the dialog will be empty because there are no elements in the array.

let groupName = 'test';
let groupIndex = 0;
let el = 'this is a test';
let result = [];

result[groupIndex + '_' + groupName] = []
result[groupIndex + '_' + groupName].push(el);

console.log('Number of elements in result array: ', result.length);
console.log('result Object Property Names: ', Object.getOwnPropertyNames(result));
console.log('result Object Property Value: ', result[Object.getOwnPropertyNames(result)[1]]);

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

A JavaScript Array is an array of course, but it is also an Object.

And more, it accept index as string without problem:

const a = [1, 2, 3]
console.log(a[0])
console.log(a['0'])

Those console.log will output the first value of the array = 1.

So the Array is wide tollerant and that is why it should be used carefully to avoid suprises in a form of very hard to debug bugs.

In your case you should use an Object or a Map.

UPDATED

Also consider that the window.alert is very different from console.log.

The window.alert attempt to print a string format of the input, that should be passed as a string, but if it is not, then it is forced.

That mean that this:

const x = {}
alert(x)

Will print [object Object]. While if you use:

console.log(x)

You will see:

{}

And you will be able to browse the object methods and attributes, even the object is empty.

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