Anonymous self-executing functions with parameters from an external scope

Recently, I stumbled upon the code snippet below while following a tutorial.

const increment = (function(){
    return function incrementbytwo (number){
        return number+2;
    }
})();

console.log(increment(1));

The result of the code above is 3.

I have a few questions about this code:

  1. How does the inner function incrementbytwo receive input from an external source if it is enclosed within a Self-Executing Anonymous Function?
  2. Can you provide a step-by-step explanation of how this code is executed?
  3. In what real-world scenario would one use a function like this?

Answer №1

When a self-executing IFFE is used, it results in the creation of a function statement that is assigned to the increment identifier. This can be thought of as equivalent to:

const increment = function incrementbytwo (number){
    return number+2;
}

Just so you know, the increment variable is block scoped within the enclosing code block (const), while incrementbytwo is function scoped and not accessible outside its own function (due to being a function expression).

In summary:

  • 1) The right-hand side is evaluated first, returning a function statement that defines incrementbytwo(number), expecting a number as an argument.
  • 2) This function statement is then assigned to increment (as a function expression). It uses the same signature as the function statement, taking a single argument to pass into the function.
  • 3) By calling increment(1), the magic unfolds.

No additional points for now.

Answer №2

My interpretation of this is as follows:

Let's begin with #2 on your list, as it will simplify things. What you have here is a self-executing anonymous function that actually RETURNS a stored function.

  1. You assign the increment constant to the result returned by executing the anonymous function.
  2. When the anonymous function runs, it returns the function incrementbytwo, which then gets assigned to the increment constant.
  3. Next, you execute the stored function within the increment constant, now known as incrementbytwo(number).

The code provided above is essentially a typical function declaration with some additional steps during assignment.

const increment = function increment(number){
        return number+2;
    }

console.log(increment(1));

As far as I am aware, there isn't a practical application for this particular code setup (feel free to correct me in the comments).

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

beforeunload event confirmation prompt

I am currently working with Laravel and Vue.js to create a multi-step wizard. Within this wizard, I have implemented the onbeforeunload event to prevent any unwanted actions by displaying a confirmation message. However, I am encountering an issue where th ...

Transform uploaded image file into a blob format and store it in a VueJS database

I am facing an issue with my form that has multiple inputs, including one of type "file". My goal is to upload an image and then submit the form to the API for storage in the database. <input name="image" class="w-full border-2 border-gray-200 rounded-3 ...

Issues with CSS not loading properly on EJS files within subdirectories

This is the structure of my folders (with views located in the root directory): views/contractor/auth/login.ejs When I access that file, the CSS styles are not being applied. The connection to the CSS file, which is located in the public directory in th ...

Utilizing Vue.js to set the instance global property as the default value for a component prop

Is it possible to access a global property from my vue instance when setting a default prop value in my component? This is what I would like to achieve props: { id: { type: String, default: this.$utils.uuid } } I attempted to use an arrow fun ...

What is preventing me from using jQuery to dynamically insert HTML onto the page?

Below is the HTML code for a Bootstrap Modal dialog box: <div class="modal fade" id="rebateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> ...

Choose a word at random from a JSON string

Utilizing JSONP, I have successfully retrieved a list of words from an external source to randomly select one for use in a game. The current source being used is as follows: function processResult(obj) { console.log(obj); var data = ...

Having trouble with material-ui installation in React, Redux, and React-Router project

Guide: https://i.stack.imgur.com/k1UMV.png Due to using redux and react router, incorporating MuiThemeProvider at the top of the chain is a bit challenging. What would be the most effective method to integrate this particular library? This is my ReactDO ...

Node.js is throwing an error stating that it cannot read the property 'id' of a null value

I have been working on upgrading my old Discord bot from Node.js version 6.x.x to 8.x.x and organizing the commands in a separate folder for better organization. The command was functioning properly with my old bot, but it seems to be encountering issues w ...

How can I easily add both horizontal and vertical arrows to components in React?

Creating a horizontal line is as simple as using the following code: <hr style={{ width: "80%", border: "1px solid black" }} /> You can customize the width, length, and other properties as needed. If you want to display an arrow ...

Safari experiencing hang after successful CORS OPTIONS request

Safari (10 - OSX El Capitan) Issue with CORS Encountering a problem with CORS while performing a POST request from an AngularJS front-end to a Laravel back-end. In Chrome and Firefox, both OPTIONS and POST requests return http status 200 OK In Safari 10 ...

Problem: The variable "$" is not defined in angular datatables causing a ReferenceError

Trying to implement Paging and sorting in my table, but encountered an error even after following all the steps mentioned here: . Tried troubleshooting the issue with no success. Ensured that all dependencies were installed properly. Below is the compo ...

Attempting to hash the password led to encountering an error

An issue was encountered: both data and salt arguments are required. This error occurred at line 137 in the bcrypt.js file within the node_modules directory. The code snippet below highlights where the problem is present: const router = require("express" ...

We were unable to locate the module '@reactflow/core' or its associated type declarations

After forking reactflow, I attempted to make some modifications but encountered a type error even without making any changes. https://i.sstatic.net/EyTZE.jpg My next step was to try "pnpm i @types/reactflow," but it did not resolve the issue. ...

Tips on transferring dynamically generated results to a user-friendly print window

After users complete a quiz, they receive their results. The client now wants to implement a "Print Results" feature that opens in a new window with customized CSS. I'm trying to figure out how to transfer the results to the new window using JavaScri ...

issue with JavaScript canvas

My task is to develop a Blackberry application, but I have limited knowledge in Java. Since the application requires drawing capabilities, I decided to use HTML5 and JavaScript instead. I started reading some JavaScript tutorials to prepare for this proj ...

I am having trouble unzipping the file

I encountered an issue while attempting to download a .zip file from Discord and extracting it using the decompress package. Despite not returning any errors, the package did not get extracted as expected. (The file was saved and downloaded correctly) co ...

Best practice for structuring an object with multiple lengthy string elements in the GCP Datastore Node Library

My JavaScript object is structured like this: const data = { title: "short string", descriptions: [ "Really long string...", "Really long string..." ] } I need to exclude the long strings from the indexes, but I ...

Tips for iterating through an array of object literals and combining values with matching IDs

Looking for a more efficient way to iterate through an array of object literals and combine values in objects with duplicate IDs. Is there a smarter approach than utilizing multiple nested for loops? Here is the sample data provided: { "theList": [ ...

What is the best way to achieve a precision of 6 decimal places in JavaScript when working with decimals?

While working on coding to round numbers to six decimal places after performing some arithmetic operations, I encountered a problem. I was iterating through the elements of an array and conducting calculations based on the array contents. To achieve roundi ...

Guide to creating a Map with typescript

I've noticed that many people are converting data to arrays using methods that don't seem possible for me. I'm working with React and TypeScript and I have a simple map that I want to render as a list of buttons. Here is my current progres ...