Is there an error thrown when a JavaScript function is executed in the following pattern: "xyz()()"?

 let calculateSum = function() {
    console.log(arguments.length);
 }
 calculateSum(1)(2)(3);

Can anyone help with resolving the "not a function" error being thrown by this script? I am running it in NodeJs environment.

Answer №1

For the code to function properly, recursiveSum must return a function.

The error occurs because you are attempting to execute the result of recursiveSum(1) as a function, but it is actually undefined. Essentially, you are trying to call undefined(2)(3).

You can make modifications like this:

function currySum(x) {
  return function(y) {
    return function(z) {
      return x + y + z;
    }
  }
}

console.log(currySum(1)(2)(3));


If you require a varying number of arguments and want to utilize currying syntax, check out some of the questions referenced by Bergi in a comment: this one, that one, another one, or here.


Alternatively, create an actual variadic function:

function sum() {
  var total = 0;
  for (let num of arguments) {
    total += num;
  }
  return total;
}

// Summing multiple arguments
console.log(sum(1, 2, 3, 4));
// Summing all numbers in an array
console.log(sum.apply(null, [1, 2, 3, 4]));

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

Creating JSON from identical user interface components

I have created a form similar to this one: https://jsfiddle.net/6vocc2yn/ that generates a JSON output like below: { "List": [ { "Id": 10, "Name": "SDB_SOLOCHALLENGE_CHALLENGE_DESC_10", "email": "<a href="/cdn-cgi/l/email-pr ...

What is the best way to randomly choose a string from an array and store it in a variable?

For instance var names = array["bob","tom","jake"]; Is there a way to choose a random name from the array and then set it as the value of a variable? var randomName = I'm not sure what code belongs here ...

Issue arises in discord.js unban command if an identifier is not provided for the unbanning process

I have been following a tutorial series on developing a discord.js bot, but I encountered an issue that I am unable to resolve. The command works perfectly when an id is given, but it fails to display the error line as expected when no input is provided, r ...

Create a custom autocomplete feature using AngularJS from scratch

I am currently working on creating my own search function with auto-complete functionality. Search MAC:<br/> <input type="text" ng-model="boxtext"> <tr ng-repeat="box in boxes | filter:boxtext"> <td>{{box.type}}</td> < ...

Bcrypt.compare failing to match the passwords

I implemented a bcrypt.compare function in my code, but I'm running into an issue where it seems to not be comparing the passwords correctly. Regardless of the input password, the function always returns a status of ok. Can someone take a look at the ...

What is the best way to show the totals on a calculator screen?

As part of my work, I created a calculator to help potential clients determine their potential savings. Everything seems to be working fine, except for the total fees not appearing for all the boxes. I believe I might be missing the correct process to add ...

Prevent page refresh when submitting a form using PureCSS while still keeping form validation intact

I'm currently implementing PureCSS forms into my web application and facing a challenge with maintaining the stylish form validation while preventing the page from reloading. I discovered that I can prevent the page reload by using onsubmit="return f ...

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Swap out an element in a list that does not correspond to any element in a separate list with a designated value

I am fairly new to Javascript and currently struggling with looping through an array and replacing items. I hope my explanation is clear. Here is the initial array: [ '1:1', 'blah', '1:2', undefined, '1:3' ...

Developing a comprehensive Java web service project with AngularJS, test-driven development/behavior-driven development, using Maven and Eclipse

Encountering some challenges while setting up a project to implement the full Java, Angular.js, TDD/BDD stack. While these challenges are not causing any major obstacles as of now, they have the potential to become one. Using Eclipse 4.6.0 Neon with WTP, ...

Ways to resolve nested structure issues within a bookshelfjs transaction

I'm looking to optimize my code by updating multiple tables in a database using a single bookshelf transaction. I'm relatively new to node.js and struggling with promises, resulting in a messy nested structure. Any suggestions on how to refactor ...

How to dynamically change the position of an input field within a form using JavaScript and jQuery

I have a form displayed on my website that looks like this: input a input b input c I am wondering if it is achievable to rearrange the order of inputs using jQuery, like so: input a input c input b However, it is important that the data is still ...

open a fresh modal by closing the existing modal using just one button

I am trying to implement a unique functionality in my bootstrap based project. I have one modal that I want to link to another modal, however, I am facing some challenges in achieving this. Currently, I am attempting to use the modal.close() and .modal(&ap ...

Dynamic addition of CSS classes to HTML elements using PHP

I'm working on developing an application that includes multiple courses. Each course is completed over a certain number of days, such as 14 days or 20 days. To visually track progress, I've implemented a step progress bar that looks like this:htt ...

text within the table is overlapping when being created dynamically in the <table> using javascript and jquery.quickflip.js

Hello everyone, I am currently working on dynamically generating a table using tabs created with jquery.quickflip.js. However, I have run into an issue where the text from one tab may overwrite values in another tab when switching between them. Below is ...

What is the best way to utilize Object.keys for formatting incoming data?

Here is the data I have: const langs = { en: ['One', 'description'], pl: ['Jeden', 'opis'], }; I want to convert it into this format: const formattedData = { name: { en: "One", ...

mouse down event causing unexpected behavior in selection handle

I'm attempting to create a gap in the rectangle by using the middle selection handle. I have two middle selection handles, and if I choose either of them, it should create a gap in the middle, dividing the rectangle into two equal halves (like curtain ...

Reposition header to the top upon clicking the button

I am trying to implement a sticky header with a scroll-triggered button that appears after a certain amount of scrolling. I want this button to move the header back to the top when clicked by the user, while keeping the page at its current position. Here ...

Exploring Crypto-JS in Google Apps Script: Decoding the Mystery of C.lib

Recently, I decided to incorporate Crypto-JS into my Google Apps Script project. After transferring all of the source files to my workspace, I encountered a problem. Specifically, when attempting to encrypt data using its AES feature, I stumbled upon an i ...

Encountering NgRx Select Issues While Trying to Access Nested Properties

I've encountered TypeErrors while using NgRx select functions to access nested properties. In my app.module.ts, I have configured the root store as follows: StoreModule.forRoot({ app: appReducer }), The selectors causing errors are related to some ...