Leveraging the arguments object within function declarations

Could someone explain why the foo function functions properly?

function foo (x,y) {
  return arguments.length;
}

However, when I call the boo function with arguments, it returns an error saying undefined is not a function.

function boo (c,d) {
  return arguments.slice(0);
}

Answer №1

parameters are not arrays, but they behave like array objects. Numerous array functions can be used on these objects because they require an object with numerical properties and a size attribute, just like parameters. By using the call method and passing the object as the this parameter, you can utilize the built-in functions:

var values = Array.prototype.slice.call(parameters);
//^ values is now a genuine array

This technique also works with other methods, such as reduce:

function total(/*...values*/) {
  return [].reduce.call(parameters, function(a, b){return a + b})
}

Answer №2

arguments is actually an object, not an array. When you print it out, you will see that it resembles an object:

function bar (x,y) {
    console.log(arguments);
}

bar(30,40);

Output: { '0': 30, '1': 40 }

According to the information on this documentation,

This object has a specific entry for each argument passed into the function, starting with an index of 0. For example, if three arguments are passed into a function, they can be accessed like this:

 arguments[0] arguments[1] arguments[2]

The object doesn't possess any properties commonly found in arrays except for length.

Therefore, trying to execute return arguments.slice(0); would result in an error because slice is associated with the prototype of an array.

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

How can I create an efficient chat system using Ajax and settimeout without causing excessive virtual memory usage?

I'm in the process of creating a chat application using AJAX that fetches data every second with setTimeout. I have drafted a basic code where there is a number that increments each second by the number retrieved from the PHP page2. Upon testing it on ...

Is there a method to refresh the entire DOM-based location without having to reload the browser window?

Is it possible to achieve smooth asynchronous page transitions without breaking existing JavaScript animations in a system like Webflow? I'm struggling to find a way to present new elements to the DOM without disrupting the animations that are already ...

Code in JavaScript using VueJS to determine if an array includes an object with a certain value in one of its elements

I have a scenario where I need to address the following issue: I have an Object with a property called specs. This property consists of an Array that contains several other Objects, each having two properties: name value Here is an example of what my o ...

Emphasize a checkbox by selecting it when another checkbox is checked

I have a question about checkboxes and highlighting the checkmarks. The issue I am facing is that I have multiple checkboxes with the same ID for different screen resolutions. When I click on the label for "Check 1" it highlights the corresponding checkmar ...

Dynamic autocomplete feature with AJAX integration for filtering in Flask

Looking for some guidance on creating an HTML form with two input fields. Check out the HTML template code below: <form role="form" action="/cities/" method="get" autocomplete="on"> <label for="#input1"><strong>Country:</strong&g ...

Debug errors occur when binding to computed getters in Angular 2

Currently, I am integrating Angular 2 with lodash in my project. Within my model, I have Relations and a specific getter implemented as follows: get relationsPerType() { return _(this.Relations) .groupBy(p => p.Type) .toPairs() ...

Determine if a specific date occurred at least one day ago using momentjs

Is there a way to determine if a specific date is at least one day (24 hours) in the past using momentjs? For example: const currentDate = moment() const isAtLeastOneDayAgo = currentDate.subtract(dateToVerify) > 1 // How can this be done? ...

Steps to create a scrollable material-ui Modal

After setting up a Modal, I encountered an issue where the text describing my app inside the modal was overflowing, making it impossible to see the top and bottom parts. To solve this problem, I want to implement scroll functionality within the component s ...

Ways to showcase a list in 3 columns on larger screens and 1 column on smaller screens

When viewing on a computer, my list appears like this: However, when I switch to a phone, only the first column is visible and the list does not continue in a single column format. I am utilizing Bootstrap for my layout, and here is a snippet of my code: ...

Is it considered best practice to call the same function within itself in a function?

function takeANumber() { let startHealth = parseInt(prompt("Please enter a positive number:")); // I am recursively calling the same function within an if block to ensure that the input is a valid number greater than zero. Is this considered good practic ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

Crushing jQuery's Sortable/Droppable

Having a little issue here. I want to be able to toggle the sortable plugin's behavior by clicking a button - basically switching between sort mode and view mode. I've attempted to achieve this with the following code: function enterSortMode(){ ...

Creating dynamic routes in express.js with fixed components

I'm exploring how to create a route in express that captures URLs like this: /events/0.json Here's what I've attempted so far (but it's not working as expected): router.put('/events.json/:id.json', isLogged, events.update) ...

What is the best approach to setting up dynamic Vue routing?

I am working on implementing dynamic routing for the website that relies on changes in agreements. Here is the path tree I have set up: const routes = [ { path: "/", redirect: "/home", component: DefaultLayou ...

Utilizing ng-model with invisible input field

UPDATED: Experimenting with a new approach: <input class="form-check-input deflog-check" type="checkbox" ngTrueValue = "1" ngFalseValue = "0" ng-value="chk_mail"> Now trying to retrieve the value in AngularJS like so: object2Edit.notification = N ...

Why does the getOwnPropertyDescriptor() method in JavaScript include custom properties that are inherited?

As I delve into the world of JavaScript and Node.js, a question has arisen regarding the Object.getOwnPropertyDescriptor() function. Let's explore the following snippet of code: var rectangle = { width: 10, height: 5, get area() { ...

Ways to showcase the outcome of a spin after each rotation

I am currently working on a spinning code snippet that allows users to spin and potentially win different amounts. The code includes functionality to prevent more than 3 spins, set random rotation values, and animate the spinning effect. However, I now wa ...

A straightforward redirection in Express involving a static file

Just starting out with Node and Express and encountering a bit of trouble. I have a static html page where users enter their username via ajax to my server, and then I want to redirect them to another html file. const express = require("express"); const b ...

Maximizing the potential of Angular forms through native FormData

Currently, I am revisiting an older project that still uses traditional methods for form submission. The HTML includes a form element with defined method and action. My goal is to submit the form in the old-fashioned way using the action attribute to post ...

Nextjs unexpectedly displays blank page upon fetching data from Firebase Firestore without any error messages

I am currently facing an issue when trying to retrieve page details from Firebase Firestore using getStaticPaths and getStaticProps in my Next.js project. Despite following the code structure correctly, I am encountering a scenario where the page appears e ...