0

Am trying to understand Maps objects in javascript, and how to use them inside an application, but there's something that i cant understand and it leads me to this question, here's my example

const myMap = new Map();

myMap.set('Name', 'John Doe')
     .set(1, function sayHello(user){ console.log(`Hello ${user}`)})

myMap.get('Name'); // output John Doe
myMap.get(1); // output [function: sayHello]

as you see above i can set a function inside the Map

  1. how can i use that function?
  2. what's the point of setting a function in a Map?
  3. are there any use cases?

I'm so confused, i will appreciate any explanation

3
  • 1
    myMap.get(1)('Bob'); Commented Sep 7, 2022 at 12:36
  • 1
    are there any use cases? many, yes. eg. a map with function could be used instead of a massive if else blocks etc. Commented Sep 7, 2022 at 12:43
  • Since we are on the topic of maps might aswell ask. Is there any difference in setting a named function inside a map vs an anonymous function? Commented Sep 7, 2022 at 12:48

4 Answers 4

2

What you've stored in the map is a function object. To understand it better, take a look at the following snippet to observe the difference between sayHello and sayHello("World"). The former is the function object and the latter is an invocation.

const sayHello = (user) => console.log(`Hello ${user}`)

console.log(sayHello);
sayHello("World");

You'd observe that the .get returns you the function object. To see it in action, you need to invoke it with ().

myMap.get(1)("World");

Among other things, maps could help you organize function objects and have, arguably, more readable code. For comparison, check the following implementations.

function calculator(operation, a, b) {
  if (operation === "add") {
    return a + b;
  } else if (operation === "subtract") {
    return a - b;
  } else if (operation === "multiply") {
    return a * b;
  }
}

console.log(calculator("add", 5, 10));
console.log(calculator("subtract", 5, 10));
console.log(calculator("multiply", 5, 10));

function calculator(operation, a, b) {
  const operations = new Map([
    ["add", (a, b) => a + b],
    ["subtract", (a, b) => a - b],
    ["multiply", (a, b) => a * b],
  ]);
 
  return operations.get(operation)(a, b);
}

console.log(calculator("add", 5, 10));
console.log(calculator("subtract", 5, 10));
console.log(calculator("multiply", 5, 10));

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the explanation, i like the example that you provided to make it clear for me to understand use cases, appreciate your answer
Instructive example BUT nearly bad practice: You are defining each operation again every time calculator() is invoked. I'd rather preferred directly invoking operations (operations.get("add")(4, 10)) or at least (if real problem complexity requires it) moving operations outside of calculator function. If, like myself, you bother on scope pollution you can wrap the whole thing in an IIFE (const calculator = (()=>{/*...*/return function calc(op, a, b){/*...*/};})();)
1

1. `myMap.get(1)(userName)

2. Several: Functions are objects that define behaviours. You can pass them as parameters as callbacks, transformation filters, etc... Storing them in a Map or just a regular object is just a matter of getting faster access when accessing by some key.

3. Lots of them. You can store not only functions in maps but even whole classes if you want even in most cases it would be more handy (and almost equally efficient) to just use a regular object.

The point is never finding use cases for a thing but having that thing in your toolbox in order to be able to use it as soon as the necessity arises. In this case, when you have a set of key-function pairs big enough.

HINT: If you are curios on more use cases, search for functional programming stuff.

Comments

0

You need to invoke the function by passing the argument like:

myMap.get(1)("user");

Comments

0
  1. If you want to use the function inside the map ( like set above ) then use like this : myMap.get(1)('name')

  2. Map accepts any key type

If the object's key is not a string or symbol, JavaScript implicitly transforms it into a string.

Contrary, the map accepts keys of any type: strings, numbers, boolean, symbols. Moreover, the map preserves the key type. That's the map's main benefit.

  1. There are specific usecases where map win the race over objects :
  • Map can contain keys of any data type, it could be Objects, integers, strings, boolean, functions or arrays. But in Objects, the key must always be a string or a symbol.
  • A Map is ordered and iterable, whereas a objects is not ordered and not iterable
  • Checking the number of entries in a Map is quite easy compared to checking that of Objects.
  • A Map inherits from Map.prototype. This offers all sorts of utility functions and properties which makes working with Map objects a lot easier
  • There are chances of accidentally overwriting inherited properties from prototypes by writing JavaScript identifiers as key names of an object (e.g., toString, constructor, etc.) at that case, use Maps
  • Another object cannot be used as key of an object, so no extra information can be written for an object by writing that object as key of another object and value of that another object will contain the extra information but this is possible in the case of Maps

and much more...

Remember! : debugging with Maps is painful then the objects

I Hope this answer helps you! Comment if you have any questions or doubts and don't forget to mark the answer as accepted if you find it useful because it'll be helpful for others who're looking the answer for the same question. Have a great day!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.