I am attempting to invoke a JavaScript function from within another function, but unfortunately, it does not seem to be functioning

I encountered an issue that is causing me to receive the following error message:

TypeError: Cannot read property 'sum' of undefined

How can this be resolved?

function calculator(firstNumber) {
    var result = firstNumber;

    function sum() {
    for (let i = 0; i <= arguments.lenght; i++) {
        result += arguments[i];
    }

    return result;
    }

    function dif() {
    for (let i = 0; i <= arguments.lenght; i++) {
        result -= arguments[i];
    }

    return result;
    }
}

var myCalculator = calculator(10);
console.log(myCalculator.sum(2, 3));
console.log(myCalculator.dif(1, 2, 5));

The expected output should be:

15

2

Answer №1

To retrieve the desired functions, access the length property of arguments and loop through < arguments.length, returning an object with the specified functions.

Keep in mind that using a variable named result retains its value from previous calculations. In this case, the initial result is 15 and later becomes 7, rather than the expected value of 2.

function calculator(firstNumber) {

    function sum() {
        for (let i = 0; i < arguments.length; i++) {
            result += arguments[i];
        }
        return result;
    }

    function dif() {
        for (let i = 0; i < arguments.length; i++) {
            result -= arguments[i];
        }
        return result;
    }

    var result = firstNumber;
    return { sum: sum, dif: dif };
}

var myCalculator = calculator(10);
console.log(myCalculator.sum(2, 3));
console.log(myCalculator.dif(1, 2, 5));

If you want the result to always include the original firstNumber, initialize the result variable with firstNumber.

function calculator(firstNumber) {

    function sum() {
        var result = firstNumber;
        for (let i = 0; i < arguments.length; i++) {
            result += arguments[i];
        }
        return result;
    }

    function dif() {
        var result = firstNumber;
        for (let i = 0; i < arguments.length; i++) {
            result -= arguments[i];
        }
        return result;
    }

    return { sum: sum, dif: dif };
}

var myCalculator = calculator(10);
console.log(myCalculator.sum(2, 3));
console.log(myCalculator.dif(1, 2, 5));

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 getTotalLength() method in SVG may not provide an accurate size measurement when dealing with non-scaling-stroke. To obtain the correct scale of

In my current project, I am utilizing JavaScript to determine the length of a path and apply half of that length to the stroke-DashArray. However, I have encountered an issue as I am using vector-effect="non-scaling-stroke" in order to maintain a consisten ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

Assign a function in one class to be equivalent to a function in a different class

What is causing this issue and how should it be resolved? class A { constructor() { console.log('constructin A') } public someMethod = (x: string) => { console.log(x) } } class B { private myA: A constructor ...

Obtain the href attribute's value from an HTML document using Javascript

I'm facing an issue here. Currently, I am utilizing Grid.js (http://tympanus.net/codrops/2013/03/19/thumbnail-grid-with-expanding-preview/) for my project. Now, my goal is to incorporate a Lightbox with multiple thumbnails inside the dropout provide ...

What method can we use to temporarily route traffic from one URL to another URL for a specific amount of time?

Is there a way to use javascript/jquery code that will redirect my website to a different domain, but only during specific hours? I'm looking to have the redirection occur between 2 a.m. and 4 a.m., so that it only works for two hours out of the day. ...

Is there a way to incorporate promises into an endless loop while adding a delay in each iteration?

require("./getSongFromSpotify")().then(a => { require("./instify")(a.artist,a.name).then(r => { if (r.status === "ok"){ console.log("saved") }else{ console.log(" ...

Add a CSS class to an innerHTML element just a single time

I currently have 2 files available: data.php page.php The data.php file is responsible for fetching a row from a SQL database and sending it to the page.php file. Within the page.php file, there is a JavaScript script that receives this row through AJAX ...

Dynamic importing fails to locate file without .js extension

I created a small TS app recently. Inside the project, there is a file named en.js with the following content: export default { name: "test" } However, when I attempt to import it, the import does not work as expected: await import("./e ...

What is the best way to iterate over my JSON data using JavaScript in order to dynamically generate cards on my HTML page?

var data = [ { "name":"john", "description":"im 22", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d7e7f0c2b212d2520622f">[email protected]</a>" }, { "name":"jessie", ...

Uploading files into an array using Angular 2

Struggling to incorporate an uploader within an array: I've got an array of users displayed in a table using "ng-repeat". I want to add a column with a button to upload an image for each user. Currently, I'm utilizing ng2-file-upload, but open t ...

Using AngularJS to access JSON files through the $http service

I'm experiencing difficulties reading data from my test.json file using the #http service. I have everything set up on a xampp localhost, but I can't seem to figure out what's going wrong. Here's the JavaScript code. Thank you in advanc ...

How can I change the "Return" button on the iOS keyboard to a "Next" button using jQuery or JavaScript?

Currently, I am developing an HTML application and working on implementing it for IOS devices such as the IPAD. Within my application, there are multiple text boxes. Whenever a user clicks on a text box to input text, the keypad appears. On this keypad, ...

Can you provide the specific URL for a Metacafe video to stream within a div container?

Could anyone assist me in finding the "Direct Url" to play metacafe videos within a div element? ...

What are the steps to verify if an iframe is lacking content?

I have two different codes: one is null and the other is not null. Code with null value (== empty): <div class="col-xs-6"> <iframe style="width:868px; height:550px;" id="FileReload" src="/Account/GetPDF?NUM=101"> <html> ...

AngularJS Form Validation Error Handling

I am in the process of implementing Form Validation using AngularJS, and I have come across a scenario involving ng-class that is confusing me. Could someone please explain why they are utilizing ng-class in this manner? The presence of a map and an arra ...

When XMLHttprequest is used to send a POST request, it sometimes

Here is the code I'm using to send a request: let ajaxHandler = new XMLHttpRequest(); ajaxHandler.onreadystatechange = function() { if(ajaxHandler.readyState == 4) { console.log(ajaxHandler.responseText); } } ajaxHandler.open("POST", ...

Can the data from these JSON elements be obtained?

Suppose I have a JSON file with the following structure: { "update" : { "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a6aea2aaaf83a4aea2aaafeda0acae">[email protected]</a>":{ "1234": {"notfication" ...

Where should the defer.resolve be placed when executing a function asynchronously in a loop using JavaScript?

As someone coming from a java/python background, I am venturing into the world of JavaScript. My current task involves creating a product list with detailed descriptions of its children included in a JSON array. Here is an example of what I want to achiev ...

Can config values be dynamically set from an Excel file in Protractor?

I am currently working on parameterizing capabilities using an Excel sheet. For this task, I am utilizing the npm exceljs package for both reading and writing data. Below is a snippet of the code that demonstrates how I am trying to achieve this: //This f ...

Is there a way to hide the borders between cells within these divs?

I am working on an application screen using Vue.js and facing an issue with the divisions between cells. I want to hide these divisions so that the lines of the items appear continuous. I attempted to modify the classes of the columns to "col-md" and "col ...