What prevents me from initializing a blank Map or Set using Object.create?

Unfortunately, the code snippet provided is not functioning as expected. Here's what I attempted:

const x = Object.create(Set.prototype)

x.has(1)

const y = Object.create(Map.prototype)

y.get(1)

I wanted a method to generate empty objects regardless of their type. What could be causing this approach to fail in providing that functionality?

Answer №1

Object.create generates a fresh standard object that inherits from the provided argument without any initialization, such as invoking the constructor.

For Set and Map, it is crucial to call the constructor because it establishes the necessary internal slots needed for the collection to operate (specifically, to store elements). These internal slots must be created alongside the object and cannot be added later on. This can only be achieved by using the constructor with the new keyword.

By utilizing Object.create, objects inherit has and get methods from their respective prototype objects smoothly. However, when these methods are called, the receiver (this value) is the standard object lacking the essential internal slots that would make it a true Set or Map, resulting in exceptions being thrown.

Answer №2

An improved method for achieving this:

invoke the new constructor function, using the object's actual contructor.

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

The medium-zoom feature is currently experiencing issues with functionality within Angular version 13

I've been attempting to incorporate medium-zoom functionality into my project using https://www.npmjs.com/package/medium-zoom Here are the steps I took: ng new medium_zoom_test (Angular 13) with routing & css npm install medium-zoom The image is ...

Creating multiple React applications using shared configuration files: A step-by-step guide

I am in the process of developing a React app, and my goal is to create multiple React apps that share the same configurations - including modules and configuration files like tailwind.config.cjs. How can I modify my environment to achieve this? My plan i ...

What could be causing the inability to apply CSS to customize form content?

I've just wrapped up creating a sign-up form, but I seem to be having trouble utilizing display:inline-block. What could possibly be the issue? The internal elements are stubbornly glued together and refuse to budge. (On another note, any suggestio ...

JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP. This is an example of my json: { 'username': 'Karl', 'email': '<a href=" ...

The failure of a unit test involving Jest and try-catch

I am facing an issue with creating unit tests using jest. exportMyData.js const createJobTrasferSetArray = async () => { const data = exportData(); const jobTransferSet = []; try { data.forEach((element) => { const JobPathArray = el ...

Utilize the UseQuery graphql function in conjunction with the useState hook within useEffect, allowing for the execution of an additional useEffect to update additional state

In my NextJS project, I am utilizing Apollo for graphQL queries and encountering an issue with the stateData.allProducts section. Despite setting the state in the useEffect and including data as a dependency in the array, the error claims it is null when d ...

vuex: initialize values using asynchronous function

My store setup is as follows: export const store = new Vuex.Store({ state: { someProp: someAsyncFn().then(res => res), ... }, ... }) I'm concerned that someProp might not be waiting for the values to be resolved. Is th ...

Tips on integrating googleapis with apps script

My goal: I am trying to implement the Google Calendar's API acl.list() in a Google Script using the UrlFetchApp.fetch() function. Issue: The Google script itself has an OAuth token when it runs. However, the problem arises when the UrlFetchApp.fetc ...

Combining two RxJs observables to create selectable options for a material drop-down menu

I'm encountering issues while attempting to combine two different observables and display the results in a Material Select component. This example (created using the Material docs tool) demonstrates what I'm trying to achieve. However, the optio ...

"Upon subscribing, the object fails to appear on the screen

Why is the subscription object not displaying? Did I make a mistake? this.service.submitGbtForm(formValue) .subscribe((status) => { let a = status; // a = {submitGbtFrom: 'success'} console.log(a, 'SINGLE ...

How can I effectively retrieve the JWT in a node environment?

I've successfully set up JWT authentication using Node.js. After the user signs in, Node.js generates a JWT and sends it back to be stored in the localStorage. However, I've encountered an issue when trying to access this token within the express ...

Creating text using the Bootstrap grid system

I am currently using Bootstrap and have set up a grid with a circle on the left side. I am now facing an issue where any text I try to add next to the circle overlaps with it. I need the text to not overlap with the circle and vice versa, while also being ...

Guide to generating interactive material-ui components within a react application?

I am facing a challenge in creating a dynamic mui grid element triggered by a button click in a React component. When attempting to create let newGrid = document.createElement('Grid'), it does not behave the same way as a regular div creation. D ...

Set $scope.model childs to an empty string or a null value

While working on a form, I am using a $http request to send the information through Angular in the following manner: $http({ method:"POST", url: "controllers/servicerequest.php", data: { servicerequest: $scope. ...

Using the shift() method in Javascript to manipulate Objects

My goal is to take my list and combine the first two items (0 & 1) together. I attempted the following code: total=foo.shift(); foo[0]=total However, I encountered this error: Uncaught TypeError: Object [object Array] has no method &ap ...

What is the best approach for designing a UI in Angular to showcase a matrix of m by n dimensions, and how should the JSON format

click here for a sneak peek of the image Imagine a matrix with dimensions m by n, containing names on both the left and top sides. Remember, each column and row must be labeled accordingly. ...

What are the steps to effectively populate a mongoose schema?

In my application, I have a model for people: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PersonSchema = new Schema({ name: String, cars: [{ type: Schema.types.ObjectId, ref: 'Cars' }] }); ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Modify the current link's <li> class

I am facing an issue with the code below which is supposed to change the class of li based on whether the browser URL matches the href attribute within that li. The current problem I am encountering is that the code changes the class for all li elements, ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...