Can functions be used as keys in a collection in JavaScript's map?

Using functions as keys in JavaScript can be tricky because for js objects, functions are converted to their "toString" form. This poses a problem if two functions have the same body.

var a = function() {};
var b = function() {};
var obj={};
obj[a] = 1;
obj[b] = 2;

In this case, the value of obj[a] will actually be 2.

However, using a Map seems to solve this issue. Here's an example:

var a = function() {};
var b = function() {};
var map = new Map();
map.set(a, 1);
map.set(b, 2);

With the Map, calling map.get(a) will return 1 and map.get(b) will return 2.

It's important to note whether this behavior is consistent across all browsers or specific to Chrome's implementation of the Map collection. Additionally, understanding how functions are hashed in maps can provide insight into why this works reliably.

Answer №1

When it comes to object property names, they must be strings. Any attempt to use a value of a different type as a property key will result in the value being converted to a string.

On the other hand, with a Map instance, things are handled differently. According to the ES2015 specification, Map keys can be of any type, providing a reliable option across environments supporting Map.

The hashing of a function value is not explicitly defined in the spec. Each function instance is unique, meaning that even if two functions have the same body, they will serve as distinct Map keys.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Next.js throws an error when trying to access the document object while using React Aria overlays

Recently, I've been diving into Next.js for web development and stumbled upon commerce, a template specifically designed for e-commerce websites using Next.js. While exploring the codebase, I noticed the Sidebar component which leverages React Aria fo ...

What is the best way to add a button to every row in Titanium Studio?

Is there a way to add a different button inside each row (createTableViewRow)? I have created five buttons using Titanium.UI.createButton, but I'm struggling to figure out how to place all five buttons in every row. Can someone provide some guidance o ...

Tips for utilizing the jQuery selectbox plugin on multiple elements within a single page

On my webpage, there are 3 select boxes that I want to customize using a jQuery selectbox plugin. However, the issue I'm encountering is that the plugin only works on the first select box and the others remain unchanged. Does anyone know why this mig ...

Is there a way to ensure that my AngularJS factory fetches HTTP data only once?

I have implemented a factory in my project to share data among multiple controllers. Here is the code for my factory: var szGetData = "some url that works"; myApp.factory('Data', function ($http) { var eventData = {}; eve ...

Modify/Adjust/Move the image uploaded by the user in VueJS before transferring it to an aws s3 bucket

Can you resize images in vuejs using vanilla js? I've managed to upload an image and send it to my s3 bucket using vue, but I'm struggling to figure out how to transform an image within vuejs and display it. Document.querySelector doesn't se ...

What is the best way to iterate through elements that come after a specific element?

I'm confident that I will be able to provide an answer to this very soon... Here's a sample code snippet: <script> function ClearAndRunFuncs(element) { //Clears responses for elements AFTER this element with an onchange //Executes the uni ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

Validate that a string is a correct file name and path in Angular without using regular expressions

Currently, I am using regex to determine if a string is a valid file name and path. However, when the string length becomes longer, it ends up consuming a significant amount of CPU, resulting in browser performance issues. public static readonly INVALID_F ...

Rhino's env.js causes the anchor element's pathname to be undefined

Encountered an issue that appears to be related to how anchor tags are implemented in Rhino. Despite using env.js, there might be a configuration error causing the problem. The issue arises when writing unit tests for code designed for an angularjs applic ...

Retrieve container for storing documents in JavaServer Pages

Previously, I created JSP and HTML code to upload a file from the hard disk into a database using <input type="file" name="upfile"> However, a dialog box with an "Open" button is displayed. What I am looking for is a "Save" button that will allow u ...

Spin the div in the opposite direction after being clicked for the second time

After successfully using CSS and Javascript to rotate a div by 45 degrees upon clicking, I encountered an issue when trying to rotate it back to 0 degrees with a second click. Despite my searches for a solution, the div remains unresponsive. Any suggestion ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

Only line breaks are permitted in Mustache.js, all other HTML characters are escaped

After a user submits input, I am generating comments and displaying them using Mustache.js. When it comes to rendering the comments, I have found that replacing user-entered line breaks (\n) with <br/> allows them to display as HTML breaks. To ...

Jest does not recognize AnimationEvent as a defined element

I am currently facing an issue while attempting to simulate an animationEvent for a test within my Angular application. The error message I receive is: ReferenceError: AnimationEvent is not defined. Given that this feature is experimental, it seems like ...

Is there a way to customize jqwidgets jQuery grid cell classes/styles based on row ID and column name?

{ text: 'sell', datafield: 'Sales', width: '3%', columntype: 'button', filterable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { return &apos ...

I am experiencing technical difficulties with my API resulting in a 500 Internal Server Error

My application involves managing products using CRUD operations. I am able to successfully make an HTTP request to the /api/deleteProduct route in order to delete a product based on its ID. However, the issue lies with creating a new product as the functi ...

Generate a dynamic add to cart section for every last configurable choice, assisting with this task

Currently, I am involved in a project that involves displaying configurable options on a product page, along with querying the database to check which vendors carry the product. The list of vendors is then displayed using JavaScript. In order to make the ...

Conceal any ng-repeat elements that do not contain corresponding grandchildren within two levels of nested ng-repeats

Apologies for the enigmatic title, but the issue at hand is quite cryptic ¯\_(ツ)_/¯ I'm dealing with a complex problem involving 3 nested ng-repeats to display Google Analytics' account structure. Within this structure are multiple acco ...

What is the best way to access a video stored in a local file on the initial page and then watch it on the subsequent

I recently encountered a scenario where I needed to select a video on one page and have it automatically play on another page without any redirection. The initial page displays a list of videos for selection, like this: FirstPage Once a video is chosen on ...

Pressing the reset button on a basic calculator

I am experiencing an issue with my calculator. It works fine initially, but after using the reset button, it stops functioning properly. Currently, I only have the multiplication set up as I debug this problem. I am new to JavaScript and would appreciate a ...