What is the process for evaluating the variable `results` in this scenario?

Can anyone provide some insight on how this code is functioning?

I grasp the concept of callbacks but during a tutorial video, I encountered this code snippet:

function addAndHandle(n1, n2, cb) {
    const result = n1 + n2;
    cb(result);
}

addAndHandle(10, 20, function (results) {
    console.log(results);
});

My question pertains to how results is calculated within the callback. Initially, the result is passed into the callback in the function declaration which seems logical as the sum is stored in result. However, later on, I utilize results, so how does it display the sum of 10 and 20 or any other values assigned to n1 and n2?

Answer №1

When the function is called, it takes in three parameters.

The values of n1 and n2 are added together within the function and stored in a variable.

This result is then passed to another function as an argument.

You may find it helpful to use different parameter names for clarity.

function addAndHandle(n1, n2, callback) {
    const sum = n1 + n2;
    callback(sum);
}

addAndHandle(10, 20, function (result) {
    console.log(result);
});

Answer №2

Perhaps presenting it in this format will aid your comprehension:

function performOperation(num1, num2, callback) {
    const result = num1 + num2;
    callback(result);
}

function displayOutput(output) {
    console.log(output);
}

performOperation(10, 20, displayOutput);

Within the performOperation function, you execute the callback - in this case, calling displayOutput with a result of 30. This is equivalent to invoking displayOutput with 30:

displayOutput(30)

Therefore, the output is calculated utilizing const result = num1 + num2, which is then passed to the displayOutput function.

In your illustration, an anonymous function is utilized as the callback, but the underlying logic remains consistent. I simply separated your original callback into a distinct function for simplification purposes.

Answer №3

It seems there may be some confusion as result and results are essentially the same in this particular scenario. Your result is passed into your callback function (

function (results) {console.log(results);}
) as results

These are the values you are working with towards the end

function addAndHandle(n1 /* 10 */, n2 /* 20 */, cb /* function (results) {console.log(results);} */) {
    const result = n1 + n2; /* 30 */
    // This line simply invokes your callback function below with the value of result, which is 30
    cb(result /* 30 */);

    // If you are familiar with IIF
    (function (results) {console.log(results);})(result);


addAndHandle(10, 20, function (results /* 30 */) {
    console.log(results /* 30 */);
});

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 make sure to consider the scrollbar when using viewport width units?

I've been working on developing a carousel similar to Netflix, but I'm facing an issue with responsiveness. I've been using a codepen example as a reference: Check out the example here The problem lies in the hardcoded width and height use ...

Ways to exchange information among Vue components?

My role does not involve JavaScript development; instead, I focus on connecting the APIs I've created to front-end code written in Vue.js by a third party. Currently, I am struggling to determine the hierarchy between parent and child elements when ac ...

What is the most effective method of utilizing union or extend in TypeScript when faced with a comparable scenario?

I have a function that takes in two different types of objects: const canBeGenericOrDefaultData = { id: 123, pointData: { square: 'x145', triangle: 'y145' } } function submitHandler(canBeGenericOrDefaultData: AllTheDatas | G ...

Retrieve the v-id-xx attribute value for scoped styling in a Vue Single File Component

When using pure JavaScript to add elements in a Vue Single File Component, the added elements are missing the v-id-xx attribute for scoped CSS. Is there a way to retrieve the component's v-id-hash value using only JavaScript? ...

GWT integration for TinyMCE

I've been attempting to incorporate TinyMCE with GWT's RichTextBox, but so far I haven't had any luck. The issue seems to be that GWT turns the Rich text area into a #document, rather than a standard textarea in HTML. Does anyone know how to ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Implementing Twain functionality in an Electron-based desktop application

I've been tasked with building a desktop application using React + Electron, and my client wants to incorporate scanning documents using a scanner and uploading them to the server through the app. Are there any effective ways to integrate Twain into R ...

Error message: JavaScript is unable to save data to an array retrieved from Ajax, resulting in

I am facing an issue with retrieving continuous data from the database using AJAX and storing it in a JavaScript variable. Despite my efforts, I am unable to populate an array with the retrieved values as they always end up being undefined. Below are the s ...

Ways to disable mousewheel function in jQuery

I am trying to deactivate the mouse scroll in jQuery and successfully did so, however, I encountered this error message jquery.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See Thi ...

Retrieving a PHP script from within a DIV element

I am seeking assistance to successfully load a PHP file from a DIV call. Below is the code I have used: <html> <head> </head> <body> <script class="code" type="text/javascript"> $("#LoadPHP").load("fb_marketing ...

Having trouble getting the HTML input textbox onChange event to fire properly?

This is the code I have been working on: <script language="JavaScript"> function toggle() { if (this.value=='1') { document.getElementById('dbOn').style.visibility='visible'; } el ...

Extracting data from a JavaScript React webpage with Python Selenium, targeting an element that disappears shortly after loading

Having trouble with scraping a webpage that features a React element hiding a dropdown after a few seconds. Upon initially arriving at the page, this is what is visible and what I aim to scrape: https://i.sstatic.net/VVY4r.jpg The specific information I ...

Unable to retrieve the iframe variable from the parent as it returns undefined

I am trying to retrieve a variable within an iframe from the parent index.html. Here is the index.html code: <!doctype html> <html lang="en-us> <head> <title>Test</title> </head> <body> <p>Test& ...

Allow JavaScript to determine whether to link to an internal or external web address

Currently, I am in the process of setting up a new website and need to create an HTML page with some JavaScript that can determine whether to link to the external or internal IP address. I have researched some JavaScript code to fetch the IP address, whic ...

What is the reason for not being able to retrieve query parameters in "getStaticProps"?

Let's simplify things: URL: http://localhost:3000/product/bioCloths?activeCategory=medium&id=0 File location: pages/product/[product].js. Expected output: product: "bioCloths, activeCategory: "medium", id: "0" using g ...

Displaying foreign exchange rates using Shield UI Chart

In my quest to access and display forex data, I have stumbled upon the incredible Shield UI Chart. After some experimentation, I successfully mastered the art of implementing ajax: $.ajax({ url: 'http://api.apirates.com/jsonp/update', dataTy ...

Encountering an issue with TS / yarn where an exported const object cannot be utilized in a consuming

I am currently working on a private project using TypeScript and Yarn. In this project, I have developed a package that is meant to be utilized by one or more other applications. However, as I started to work on the consumer application, I encountered an ...

Embedding Vue component into a traditional PHP/jQuery project

Currently, I have a large legacy web application that is primarily built using Codeigniter and jQuery. Our strategy moving forward involves gradually transitioning away from jQuery and incorporating Vuejs into the project instead. This process will involv ...

What methods can I use to adjust my HTML content once I have parsed my JSON file?

<script type="text/javascript"> window.alert = function(){}; var defaultCSS = document.getElementById('bootstrap-css'); function changeCSS(css){ if(css) $('head > link').filter(':first').replaceWit ...

Why does xpath insist on choosing spaces instead of actual elements?

Here is a list of countries in XML format: <countries> <country> <code>CA</code> <name>Canada</name> </country> ... etc... </countries> I am looking to extract and loop through these nodes, so ...