-2

Can you clarify why boolean is used while adding objects to the WeakMaps in the code below. I understand set takes two(key and value) arguments. The boolean values gets printed in the console as well…that is my doubt…

Thanks in Advance.

const book1 = { title: 'Pride and Prejudice', author: 'Jane Austen' };
const book2 = { title: 'The Catcher in the Rye', author: 'J.D. Salinger' };
const book3 = { title: 'Gulliver\'s Travels', author: 'Jonathan Swift' };

const library = new WeakMap();
library.set(book1, true);
library.set(book2, false);
library.set(book3, true);

console.log(library);

WeakMap {Object {title: 'Pride and Prejudice', author: 'Jane Austen'} => true, Object {title: 'The Catcher in the Rye', author: 'J.D. Salinger'} => false, Object {title: 'Gulliver\'s Travels', author: 'Jonathan Swift'} => true}
Gonzalo Bahamondez
  • 1,371
  • 1
  • 16
  • 37
praveen-me
  • 486
  • 3
  • 10
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/set - you pass a key and value – VLAZ Apr 29 '18 at 16:23
  • Then why should be use true and false value to them Nina – praveen-me Apr 29 '18 at 16:24
  • 4
    @PraveenKr.Saini Why wouldn't you? You can pass anything as the value, in this case it's booleans. As to why these were chosen in the example code you posted, you need to ask the author of the code not us. – Bergi Apr 29 '18 at 16:26
  • I don't think you understand what is a map? key is book1 and value true. – Amir Raminfar Apr 29 '18 at 16:29
  • *"that is my doubt"* is definitely not a real question or descriptive concern. It's important to define your issue in specific terms See [ask] – charlietfl Apr 29 '18 at 16:31

1 Answers1

0

The WeakMap isn't just storing the objects (that's a Set - different from .set).

It's making a relationship between two things, the key and the value. book1 is used as a key for the value true.

Just like in a plain object var obj = { daysInWeek: 7 }, the string daysInWeek is related (mapped!) to the number 7, so that obj["daysInWeek"] === 7.

Arrays are similar too - numbers (indexes) are mapped to values; var arr = [ "praveen" ] maps the number 0 to the string "praveen", so that arr[0] === "praveen".

Maps and WeakMaps are the same, but the keys are not limited to being strings or numbers, they can be objects as well. So library.get( book1 ) === true.

Ben West
  • 4,398
  • 1
  • 16
  • 16