Understanding the reason behind the error when utilizing `Number.prototype.valueOf` within a `map()` without an optional argument

After coming across this particular question, I decided to experiment with modifying the code that generates an array filled with zeroes:

Array.apply(null, Array(10)).map(Number.prototype.valueOf, 0);

Wanting to deepen my understanding of the map function in JavaScript, I attempted to use fill instead. However, upon executing the following in Chrome's developer tools, I encountered an error:

Array.apply(null, Array(10)).fill(0).map(Number.prototype.valueOf);

Uncaught TypeError: Number.prototype.valueOf is not generic

My comprehension of the map function leads me to believe that it should execute the callback on each element of the array using that element as its argument. The creation of the array seems to be successful with

Array.apply(null, Array(10)).fill(0)
, so theoretically it should be running Number.prototype.valueOf(0). Why then does it result in an error?

Answer №1

Why is the error occurring when trying to execute Number.prototype.valueOf(0)?

Actually, the map callback is called without a specified (undefined) this argument if none is passed to map. It receives the array element, index, and array as arguments. Therefore, it effectively executes

Number.prototype.valueOf.call(undefined, 0, 0, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

However, valueOf should only be invoked on numbers or instances of Number, otherwise it will result in an error.

Answer №2

MDN states that the map method has two parameters, with the second one being

Value to use as this when executing callback
. So when you execute the following:

Array.apply(null, Array(10)).map(Number.prototype.valueOf,0);

You are essentially calling Number.prototype.valueOf.call(0), which will always return 0. When a function that always returns 0 is passed to map, it generates an array filled with 0.

If you remove the second parameter like so:

Array.apply(null, Array(10)).map(Number.prototype.valueOf);

An error is thrown:

Uncaught TypeError: Number.prototype.valueOf is not generic(...)

To determine the default value of this in your environment for map, try running:

[0].map(v=>{console.log(this);}) // =>Window for chrome developer tools

Then test this:

Number.prototype.valueOf.call(window)

You may receive the same error message.

Answer №3

The second parameter utilized in the map function serves as a reference for this. In this specific scenario, this constantly represents the number 0 (which is then converted into an object Number(0))

Ultimately, when the map function calls Number.prototype.valueOf with this being Number(0), it essentially equates to Number(0).valueOf(), resulting in the value of 0.

(Not Number.prototype.valueOf(0) - attempting Number.prototype.valueOf(1) will demonstrate this concept further)

On the other hand, if you fail to provide the this argument in map(), it defaults to window. Consequently, calling Number.prototype.valueOf on the window leads to confusion and triggers an error. The fact that 0 acts as the argument becomes irrelevant since Number.prototype.valueOf() does not accept any arguments. Therefore, Number(0).valueOf(1) still returns 0 due to the disregard for the additional argument.

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

Ways to fetch additional Product Cards using JSON and a nextPage parameter

I'm facing difficulties in nesting a fetch inside another fetch. I'm not sure if this is the correct approach, but my goal is to utilize Vanilla JavaScript to fetch another JSON from the nextPage URL within the JSON list when the "load more" butt ...

The conversion of Draft-js JSON to EditorState is not functioning correctly

Recently, I utilized Draft-js to generate blog posts. When a user creates a post, the data is transformed into a string and dispatched to the server for storage. The conversion of draft-js EditorState looked like this: JSON.stringify(convertToRaw(editorSta ...

The interaction between a JavaScript function call and C# is not functioning properly

Attempting to invoke the JavaScript function from CodeBehind ( C# ) : function scrollToBottom() { window.scrollTo(0, document.body.scrollHeight); } The function successfully executes when directly called from my asp.net application. However, ...

Exploring Javascript Bootstrap Table Data for Cells and Columns

Struggling to retrieve the table values accurately. Is there a way to access the header value of the cell I click on? Additionally, how can I obtain the Uid based on the cell clicked, like getting the Uid of a person when clicking on their name? https://i ...

Component html element in Angular not being updated by service

Within my Angular service, I have a property linked to a text field in a component's HTML. Oddly, when this property is updated by the service, the new value doesn't reflect in the HTML element unless the element is clicked on. I'm perplex ...

Find the variance between the initial time and the present time, as well as the final time and the current time

If a user logs in before the start time of a game, they will receive a message indicating that the game will start in 01h:10m:23s. If the user logs in after the start time but before the end time, they will see a message stating that the game closes in 0 ...

Using VueJS to pass props to route components via this.$router.push

Router Configuration Example : const routes = [ { path: '/' , redirect: '/login'}, { path: '/chat', component: MyChat, props: true}, { path: '/login', component: MyLogin}, ] Defining the Chat Component ...

What exactly is the function of passport.authenticate when it is called on a callback

I have integrated passport js into my express project. The initial route presented below is responsible for creating the user in my database and subsequently redirecting to the second callback route. What does the function 'passport.authenticate(&apo ...

Incorporating d3-force-3d computations into a three-dimensional graph visualization tool

Looking to create 3D force directed graphs for my project, but struggling to find a library that incorporates d3-force-3d calculations. The existing libraries I've come across lack the ability to customize forces, particularly 3d-force-graph. Is ther ...

Is it possible to execute a URL twice instead of just once in AngularJS?

While developing a web application with AngularJS and Rest Web services, I encountered a problem where the URL is being executed twice instead of just once. I have created a service function for executing the web service API and calling it from the control ...

What is the method for creating arrays containing elements that fall within specified ranges defined by two arrays in Numpy?

Given two arrays of integers, min and max, with the same shape, how can I generate all Numpy arrays where each element satisfies the condition min[indices] <= ar[indices] <= max[indices] for all indices in np.ndindex(shape)? I have explored various N ...

There are over 30 player objects in the game

Imagine I have a group of players stored in an ArrayList, and I am looking to identify the players who are older than 30 years. Each player has attributes like name and age, along with corresponding methods getName() and getAge(). Since I'm a beginner ...

HTML5sortable is causing JavaScript to run twice when the sortupdate event is triggered

Having a sortable list on my aspx page, created using this specific plugin, I encountered an unusual issue. <ul id="sortableQueue" class="sortable"> <li style="cursor: move" data-shotid="1">Shot Name - 1</li> <li style="cursor ...

Delete the content on a webpage using an Ajax jQuery request to transfer it elsewhere

Whenever I submit a form using an ajax post request, I receive values from the controller and manipulate the page based on those values. However, my issue is that I need to erase the values from the previous request when the form is submitted again. For in ...

Is there a way to retrieve the Telerik HtmlAttributes values through javascript?

How can I retrieve HtmlAttributes values from a Telerik DropDownList? While I am familiar with using jQuery for this task, I would like to know the correct method for querying these values. @(Html.Telerik().DropDownListFor(model => model.BookingOff ...

What is the best way to send a file object to a user for download?

When working within a route: app.get('some-route', async (req, res) => { // ... } I am dealing with a file object called file, which has the following structure: https://i.stack.imgur.com/ByPYR.png My goal is to download this file. Cur ...

Using Angular expressions, you can dynamically add strings to HTML based on conditions

I currently have the following piece of code: <div>{{animalType}}</div> This outputs dog. Is there a way to conditionally add an 's' if the value of animalType is anything other than dog? I attempted the following, but it did not ...

Is there a way to obtain metadata for a specific link?

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><$BlogPageTitle$></title> <meta property="og:title" content=" ...

Dynamically add Select2 with a specific class name: tips and tricks

I need help adding a new row with a select2 instance using a class name. The new row is created with the select dropdown, but I am unable to click on it for some reason. var maxGroup = 10; //add more fields group $(".addMor ...

Can flexbox elements be animated as they scroll?

Wondering if it's feasible to animate flex elements upwards when scrolled? Attempting to replicate this effect: https://codepen.io/Sergiop79/pen/bxjGEe I want to apply this to the elements below (styled in flexbox), either the entire "row" or each i ...