Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Introducing ES2015 Objects and New Collection Types Map

Kayc M
Kayc M
12,593 Points

Can't log map using template literals, why?

let joe = { name: 'joe', age: 20},
ann = {name: 'ann', age: 20 };

let classroom = new Map()

classroom.set('joe', joe)
classroom.set('ann', ann)

console.log('print map: ', classroom)
output:
// print map:  Map(2) {
  //   'joe' => { name: 'joe', age: 20 },
  //   'ann' => { name: 'ann', age: 20 }
  // }


  console.log(`print map: ${classroom}`)
  output:
  // print map: [object Map]

2 Answers

Steven Parker
Steven Parker
208,480 Points

Modern browsers may evaluate the arguments to the "log" method and invoke a special conversion designed to display that type of object, but the template string relies on the object's own string conversion method.

So:

console.log(`print map: ${classroom}`);              // is equivalent to...
console.log('print map: ' + classroom.toString());
Kayc M
Kayc M
12,593 Points

But why does concatenating without "toString" have the same result

console.log('print map: ' + classroom);
output:
  // print map: [object Map]
Steven Parker
Steven Parker
208,480 Points

Concatenating a non-string onto a string also invokes the built-in (toString) conversion. What the browser does for you when it is a separate argument is a new feature above and beyond the language itself, and not long ago in previous versions would have looked the same as the others.