What is the reason for function f returning the display function instead of the x value?

Hello, I have a question about this code snippet. Can you please explain why it is returning a function instead of the x value? Thank you in advance.

function f() {
  function createClosure(x) {

    return function(){
      return x;
    };
  }
  var arr = [];
  var index;
  for(index = 0; index < 3; index++) {
    arr[index] = createClosure(index);
  }
  return arr;
}
var result = f();
console.log(result[0]);

Answer №1

createClosure is a function that generates other functions, resulting in an array b filled with these generated functions.

Calling b[0] will retrieve the function itself, while invoking b[0]() will return the result of x.

Answer №2

Upon examining the function makeClosure, it is evident that it produces a function which, when called, yields the value of x.

Inside the loop, the statement a[i] = makeClosure(i); stores the function generated by makeClosure(i) at the specified index i within the array.

By executing a function stored at a specific index in the array, you can retrieve the corresponding value of x.

Therefore, calling a[0](); is expected to result in 0.

Answer №3

When you call the function f(), it will give you back an array.

By doing var a=f(), you are storing that array in variable a.

Each element inside the array is actually a function. So if you try to access any element in the array a, you will only get the function definition and it won't run automatically.

To execute the function, you must treat the elements in the array as functions. For example, instead of just calling a[0] like this console.log(a[0]);, you should call it like this: console.log(a[0]());

This was the main purpose...

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

Looking to generate flipcards dynamically through javascript or jquery when a button or link is clicked?

I've created flipping cards that flip on hover, but I'm struggling to add a button/link that generates a new flipcard when clicked. Any help would be greatly appreciated - plus, I'm new here! Here's my HTML and CSS code for the flipcard ...

Encountering an error with my electron application built using create-react-app

While I'm working on my project, my electron window is showing this error message. TypeError: fs.existsSync is not a function getElectronPath ../node_modules/electron/index.js:7 4 | var pathFile = path.join(__dirname, 'path.txt') 5 | ...

I am experiencing unexpected results with my Mongoose filter and sort query in Express JS middleware. The output does not match what I am anticipating, and the sorting functionality seems to

This middleware is used for filtering and sorting data. I made some modifications to it, but it's not functioning as expected: const aliasTopMenu = (req, res, next) => { req.query.sort = '-price'; req.query.fields = 'name,price, ...

Discover an Element within a JSON Array and Append a New Value to it

I've got an array of JSON data structured like this: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Eve' } ] My goal is to locate an object by its id and append a ...

Describing how to assign multiple variables in a VUEX mutation

store.js import Vue from 'vue'; import Vuex from 'vuex'; import userStore from './user/userStore.js'; import VuexPersist from "vuex-persistedstate"; Vue.use(Vuex) const debug = process.env.NODE_ENV != ...

Is there a way to remove "gsi" from a string and replace it with an empty string in JavaScript?

I need to modify a string by removing the substring gsi and its value. The desired outcome should be: Scenario 1 /product/Abrasives?gsi=1 Expected output /product/Abrasives Scenario 2 /product/Abrasives?query=search&gsi=1 Expected output /product/A ...

steps for linking a directive variable to a controller

Encountering an issue with 2-way binding in Angular where changes made to the input do not reflect in the controller. However, the initial value set by the controller does affect the directive. In the screenshot, a value was changed but vm.date still hold ...

Creating beautifully formatted PDFs using pdfmake in AngularJS

I have a HTML popup displaying data retrieved from the server, and I am attempting to download this data as a PDF using the pdfmake plugin. While I am able to generate the PDF file, the challenge lies in replicating the HTML page layout in the PDF. Here is ...

Exploring the depths of JavaScript JSON elements

After processing my PHP code, it generates a JSON output that contains multiple entries in the same structure. Here is an example with two entries: { "0": { "campaign_id": "31", "title": "new title", "description": "new descrip ...

Creating a program to ascertain whether two integers inputted by a user are odd numbers

I need assistance in creating a function that can ascertain whether two numbers input by the user are odd and then return a boolean value that is true only if both numbers are odd. I'm already familiar with creating a function to check for even number ...

Implementing Cross-Origin Resource Sharing (CORS) in play-framework version 2.5.x: A Step-by-Step Guide

My current challenge involves retrieving JSON data by sending a request to a Restful URL from localhost within an AngularJS-1 application. The error that I encounter is as follows: http://localhost:9000/mlm/user/all Failed to load resource: the server r ...

What's the issue with this brief snippet of JQuery code that contains an error?

Recently, I attempted to implement a script to achieve the masonry effect on my website. The script I used is from $(function() { $("#new").masonry({ itemSelector: ".element", columnWidth: function(containerWidth) { return containerWidth ...

How can I properly choose distinct values for an individual attribute from a JavaScript array containing objects?

Let's imagine a scenario with an array of JavaScript objects like this: var data = [ {category : "root", type: "qqqqq", value1: "aaaaa", value2: "zzzzz"}, {category : "root", type: "qqqqq", value1: "aaaaa", value2: "xxxxx"}, {category : " ...

Referencing a JavaScript source in the vendor file in Rails 4: Tips and Tricks

After realizing that my GMaps for Rails setup needs amendment, I've decided to insert javascript files directly into my app. Rails 4 - Gmaps4Rails - map won't render I've downloaded the infobox and markerclusterer repositories and now find ...

Tips for handling the response after a view has been submitted on Slack using Bolt.js

Hey there! I added a simple shortcut to retrieve data from an input, but I'm facing an issue after submitting the view. The response payload is not received and the view doesn't update to give feedback to the user. Check out my code below: const ...

I am searching for a straightforward Rails sample that incorporates Ajax

Currently, I am on a quest to find a solid demonstration of how AJAX and JSON interact with Rails. I have a Rails application that relies on standard forms and I am looking to enhance it with some ajax functionality. Unfortunately, I haven't come acro ...

Executing multiple commands using Node.js TCP communication

I have established a connection to a serial device via the internet using an ethernet to serial device. The communication is facilitated through a small node.js application. The provided code retrieves the necessary information: var net = require('ne ...

Implementing Vuejs sorting feature post rendering

Currently, I have elements linked to @click event listeners. <th @click="sort('dateadded')" class="created_at">Date Added I am looking for a way to automatically trigger this sorting function when the Vue.js component renders, so that th ...

Is it really not feasible to retrieve a file using an AJAX request in ASP.NET MVC5?

While it may be more common to use a normal call instead of an AJAX call, there are instances where using AJAX is necessary, such as displaying an error message on a modal dialog during a download process. In my MVC5 project, I needed to download a file us ...

Condition formulation using dynamic dust JS equality

I'm struggling with a seemingly simple task - dynamically changing the @eq condition. The example provided shows a default render, but what I really need is to allow user input to change it to either "Larry" or "Moe". You can view my code on jsfiddle ...