The use of functions and parentheses in Javascript

I'm having trouble understanding how the f() functions work. Could someone please explain why it prints two '1's? I know it prints '1' for every '()' after f(f), but I don't understand the reasoning behind it.

function f(y) {
  let x = y;
  var i = 0;
  return () => {
    console.log(++i);
    return x(y);
  };
}
f(f)()();

Also, I'm confused about why the 'i' value does not increase.

Any help would be greatly appreciated.

Answer №1

function f(y) {
  let x = y;
  var i = 0;
  return () => {
    console.log(++i);
    return x(y);
  };
}
f(f)()();

can also be written as

function f() {
  var i = 0;
  return () => {
    console.log(++i);
    return f();
  };
}
const t1 = f();
const t2 = t1();
t2();

Alternatively, it can be simplified to

function f() {
  var i = 0;
  return () => {
    console.log(++i);
  };
}
const t1 = f();
t1();
const t2 = f();
t2();

If you were to call either t1 or t2 multiple times, the i value in their respective closures would increment accordingly. However, chaining them would result in calling f again, initializing a new var i = 0 for a different closure.

Answer №2

Initially, the f(y) function essentially invokes y on itself. When you call f(y), it generates a fresh function that, upon execution, will perform x(y) and yield the output.

To clarify, just substitute f(f) for each f() that you execute in this instance, considering that x === y and y === f. The reason i seems to remain stagnant is because each execution produces a new i.

Below the surface, the following actions take place:

    f(f)()();
    // equates to 
    const f1 = f(f);
    const f2 = f1();
    const f3 = f2();
    // initial execution of f(f) occurs first, yielding () => {
    //     console.log(++i);
    //     return x(y);  // essentially returning f(f) in this scenario
    // }

Observe that running f(f) results in x(y), where x(y) appears to be identical to f(f). Though they look similar in code, they are distinct instances. Furthermore, i does not transfer to this new function, nor does it carry over to other instances. Each f(f) generates a fresh i, without passing it on to subsequent functions.

Answer №3

Let's call the function on line 4 "function A".
Instead of calling function f() inside function A, you define it at line 4 and then return the result of function A.
The contents of function A are as follows, with variables i = 0 and x = y = f not being exposed due to their use in an inner function:

function A() {
console.log(++i);
return x(y);

Therefore, what you now have is: A()().

Within the first set of parentheses: A() will print a '1' and return the result of f(f), which is function A (the initial i is exposed and a new i is created).

Within the second set of parentheses: A is executed as previously mentioned and returns another instance of A. Since there are no more parentheses left, there will be no further function calls.

Answer №4

In the function f, a new i is declared every time.

Instead of that, you could save the count as a property of the function itself.

function f(y) {
    let x = y;
    f.i = f.i || 0;

    return () => {
        console.log(++f.i);
        return x(y);
    };
}

f(f)()()();

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

Tips for successfully uploading FormData files using Axios: Resolving the TypeError of "file.mv is not a function"

When transmitting a file from one server to another using Axios, I am facing an interesting scenario where one server is an app backend and the other is a blockchain server. The destination for the file transmission is set up as follows: router.post("/a ...

What is preventing me from using memoization in the getServerSideProps of NextJS?

I'm currently using React along with NextJS to showcase a variety of products on a specific category page. While I am able to successfully fetch the products utilizing getServerSideProps, I am not fond of how it continuously requests the product cata ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...

Issue with redirecting to another link in Angular routing

After numerous attempts, I finally managed to configure the adviceRouterModule correctly. Despite extensive research and Google searches, I couldn't quite crack it. Here is the configuration for my AdviceRoutingModule: const adviceRouters: Routes = ...

Angular ngClass and ngIf directives failing to update upon alterations

In my current Angular project, I am working on a functionality where I need to dynamically change a class based on a variable without having to refresh the page. I have experimented with *ngIf/else and [ngClass] directives, which do work, but unfortunatel ...

Coloring the table upon selecting a checkbox using AJAX, JavaScript, and JSP

How can I adjust the color of the entire table (every row of the table)? Currently, I can only change the color of the first row of my table. Here is my color function in JSP: function changeColor(rowID){ var row = document.getElementById(rowID); ...

Updating React state by changing the value of a specific key

I've been diving into React lately and I'm facing an issue with updating state values for a specific key. Below is my current state: this.state = { connections : { facebook : "http://facebook.com", flickr : null, ...

Node.js program closes immediately upon Java startup

I am building a Discord bot that features a Java FXML interface and utilizes a Node.js program to function as an Audio playing bot. However, I am encountering an issue where the process for Node.js closes immediately when opened in Java. The problem arise ...

What is the most effective method to include JSON data containing various IDs at the end within an $http.get() request in AngularJS?

I'm facing a challenge with displaying JSON items that have an array of different ids at the end of the URL (/api/messages/:messageId). For instance, accessing /api/messages/12345 would return {"subject":"subject12345","body":"body12345","id":"12345"} ...

`Inconsistencies between Postman and AngularJS service responses`

When I make a call to the endpoint using Postman, I receive this response: https://i.stack.imgur.com/pH31G.png However, when I make the same request from my AngularJS service defined below: this.login = function (loginInfo) { return $http({ ...

Creating a heading transition that moves from the bottom to the top with CSS

I am looking to add an animation effect to the H1 element in my program. I want it to smoothly appear from the bottom hidden position using a CSS transition when the page loads. How can I achieve this? Additionally, I need the height of the bounding elemen ...

Unable to display nested JSON data from API in Vue.js

Having trouble accessing nested properties from API JSON data. The Vue component I'm working on: var profileComponent = { data : function() { return { isError : false, loading : true, users : null, ...

The Mongoose findOne function encountered an error when attempting to convert a value to ObjectId

Trying to solve a perplexing exception that has left me scratching my head for over an hour. Error message: CastError: Cast to ObjectId failed for value "[email protected]" at path "_id" for model "Account" My goal is to fetch an Account using the ...

Loop through the input fields using ng-repeat while maintaining consistent values for each iteration

I am facing an issue with my ng-repeat loop where I have a comment input inside it. The problem is that when I start typing in the first input, the text appears simultaneously in all other inputs as well. I have tried adding a unique ID but it didn't ...

Leveraging Variables within my .env Configuration

Does anyone have suggestions on how to set variables in my environment files? Website_Base_URL=https://${websiteId}.dev.net/api In the code, I have: websiteId = 55; and I would like to use config.get('Website_Base_URL'); to retrieve the compl ...

Accessing component variables within an event in Angular 2 (dealing with scope problems)

I am currently facing an issue with scoping in my component click event. Specifically, I need to access private variables within the component, but the keyword this now refers to the event scope rather than the component's. This has led to an error wh ...

Initiating a AJAX upload upon selection of a specific option from a select menu

Recently, I have been exploring ways to enhance my layout page by implementing an option for users to upload new logos on the spot. Currently, users are able to choose their desired image through a drop-down selection feature. I am interested in adding a f ...

Issue with the Jquery rich text plugin in Internet Explorer causing functionality problems

I have encountered an issue while trying to use a jQuery richtext editor in Internet Explorer. Interestingly, it fails to work in IE but functions properly in Chrome. Here is the code snippet where I call the plugin and it works well in all browsers excep ...

Sending values to URL using the <a> tag in HTML

I currently have the selected language stored in a variable (var lan= urlParam('language')). I am trying to pass this language as a parameter (without PHP) in a URL within an "a" tag, like so: <a href="http://hotelscombined.sitewish.gr/HotelN ...

Vanishing Submenus

I'm experiencing an issue with my navbar and its drop-down menus. When I hover over the submenu, it doesn't stay visible as expected. I've tried different approaches such as using jQuery, the + operator in CSS, and even creating a separate h ...