Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array is behaving differently in Nodejs and browser

I have this snippet of code :

let a = {};
a.x = 'John';

let b = [];
b['y'] = a;
console.log(b);

a.x = 'Dan';
console.log(b)


I ran this code in NodeJS using command line and ran it in Chrome browser console.

The result : in NodeJS, the result was [ y: { x: 'John' } ] [ y: { x: 'Dan' } ] NodeJS result

The result : in Chrome browser console, the result was : [ y: { x: 'Dan' } ] [ y: { x: 'Dan' } ] Browser result

Why it is giving different results in node and browser console? Can anyone please explain what is really going on here?

like image 700
Apratim Avatar asked Dec 20 '20 18:12

Apratim


2 Answers

The chrome browser console shows you the live value of the object, that is it updates the values displayed as it changes, the node js console doesn't do this.
So when you did the first console.log it would show the same as in node but when you changes the value of a it was updated in the first console.log.

like image 59
Musa Avatar answered Nov 08 '22 08:11

Musa


There are two things happening here.

  1. Chrome console by default shows unexpanded object inside an array - [y: {...}]
  2. Chrome console seems to track the value of the variable and show the updated value when you click to expand the log.

If you need to check that logs are in fact the same as in node.js, you can use JSON.stringify() or console.table() instead of console.log()

like image 1
Bexultan Zhadyrassynov Avatar answered Nov 08 '22 09:11

Bexultan Zhadyrassynov