Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two different outputs using the + vs , concatenating methods

While working on this example at MDN site explaining the filter method:

var arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  { },
  { id: null },
  { id: NaN },
  { id: 'undefined' }
];

var invalidEntries = 0;

function isNumber(obj) {
  return obj!== undefined && typeof(obj) === 'number' && !isNaN(obj);
}

function filterByID(item) {
  if (isNumber(item.id)) {
    return true;
  } 
  invalidEntries++;
  return false; 
}

var arrByID = arr.filter(filterByID);

console.log('Filtered Array\n', arrByID); 
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]

console.log('Number of Invalid Entries = ', invalidEntries); 
// Number of Invalid Entries = 4

This gets output in FireBug, as expected:

Filtered array

[Object { id=15}, Object { id=-1}, Object { id=0}, Object { id=3}, Object { id=12.2}]
Number of Invalid Entries: 4

But I initially, errantly but intentionally typed the first console.log(); statement as:

  console.log('Filtered array\n' + arrById);

and got this FireBug output:

Filtered array
[object Object],[object Object],[object Object],[object Object],[object Object]

Number of Invalid Entries: 4

Why the different outputs?

like image 697
chaoticmite Avatar asked Mar 05 '17 12:03

chaoticmite


2 Answers

Concatting with the + calls toString method on the obj and so returns the string 'object' instead of returning the obj property (name: value) as is returned using the , to concat by the console.log() output.

like image 156
commnux Avatar answered Nov 14 '22 19:11

commnux


Take this simple object:

var obj = {
  test: 5,
  another: 'hello'
}

If you do this console.log(obj), what you are asking firebug to do is log your object. It knows how to deal with an object in a nice way, showing you all the properties and values.

However if you do this console.log(obj.toString()), you are asking javascript to convert your object to a string before asking firebug how to display it. Being a string, firebug will simply display it as is. So the real question is, why does javascript convert an object to a string like [object Object] ...?. You can see an explanation here

In your question, by using the +, you are forcing the object to be converted to a string so that it can be concatenated with the 'Filtered array\n' bit.


If you want to do what you have put in your question, but still have somewhat useful outputs, you can try JSON.stringify(). For example: console.log('Filtered array\n' + JSON.stringify(arrById));

like image 44
Matt Way Avatar answered Nov 14 '22 20:11

Matt Way