javascript design pattern - achieving unexpected outcome

In the code snippet provided, the variable a is turning out to be undefined. Are you expecting it to display the parameter value passed in the parent function?

function test(a) {
    return function(a) {
        console.log('a is : ' + a); // Output: a is undefined
    }();
}

test('Should "A" not be undefined? '); 

Answer №1

If you want to fix the issue, simply remove the a parameter from the closure:

function test(a) {
    return function() {
       //          ^^
        console.log('a is : ' + a);
    }();
}

There are much better explanations available than this, but I'll give it a go: test is returning a function (closure) that "captures" the environment (or scope) in which it lives, including all variables, and takes them with it. Because you were passing in an argument to that function, the console.log was expecting it. But because it was an immediately-invoked function, you either needed to pass in a to the function (like Aravinder shows in his/her answer), or don't, and just allow the closure to use a that was "passed to it" from the parent function.

Hope that was helpful.

To be fair, that's not a pattern you usually come across (or, at least, I don't). You're more likely to see something like this. Here bob is a function that contains a because a was returned along with the closure when test was called.

function test(a) {
    return function() {
        console.log('a is : ' + a);
    };
}

var bob = test('A should not be undefined?');
bob();

Answer №2

To ensure that variable a is passed as a parameter for the self-invoking function, you can modify the code like this:

Take a look at this revised snippet:

function test(a) {
    return function(x) {
       console.log('value of a: ' + x); 
    }(a);
}

test('Am I correctly passing the value of a?'); 

Answer №3

The main issue here is that the variable a inside the console.log refers to the parameter of the inner function, not the one from outer function. To clarify this situation, it would be helpful to rename the parameter of the inner function, a process known as α-conversion in lambda calculus:

function test(a) {
    return function(b) {
        console.log('b is : ' + b); // Output: b is undefined
    }();
}

test('A should not be undefined? ');

To solve this problem suggested by @andy, simply remove the parameter from the inner function. This way, the variables from the outer function will still be accessible and used instead.

Answer №4

Explaining a new concept, a represents a local variable within an inner scope that overrides the a passed to a test method.

This can be illustrated with the following example:

function test(a) {
    return function(a_inner) {
        console.log('a_inner is : ' + a_inner);
    }(); // <--- here
}

Upon creating the function, it is executed without any parameters (as indicated by the comment "here") - resulting in the inner a being undefined. To achieve the desired output, you need to pass your a as a parameter like this:

function test(a) {
    return function(a) {
        console.log('a is : ' + a);
    }(a); // <--- and again, here. it works now
}

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

Creating a list repeater using v-for in Vue.js 2 with computed property

Seeking assistance with adding computed columns to a table (last three columns). Suspecting the issue lies in the computed property not correctly referencing the record. Any simple solutions that I might be overlooking? Appreciate any thoughts or insights! ...

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...

Building secure and responsive routes using next.js middleware

After setting up my routes.ts file to store protected routes, I encountered an issue with dynamic URLs not being properly secured. Even though regular routes like '/profile' were restricted for unauthenticated users, the dynamic routes remained a ...

Having trouble accessing data in Laravel and Vue JS views

I'm currently working on displaying table data in a view using Vue.js and Laravel. Here is what I have attempted so far: This is the comment controller: public function index() { $comment = Comment::Latest()->paginate(10); return new Comm ...

Leveraging ng-hide in Angular to show or hide elements based on the state

Is there a way to utilize the ng-hide directive based on the value selected in a dropdown menu? Specifically, I am looking to display #additional-option if option C is chosen from the dropdown list. <div class="form-group"> <label class="co ...

Angularjs - Repeatedly reloading identical images

Whenever I use ng-src in the <img> tag and change the ng-src by clicking next or previous buttons, the browser reloads the image even though it's already loaded. This results in a not-so-smooth experience as the image is downloaded again before ...

What is the best method for adding a JSON array with objects to an already existing table?

After incorporating Bootstrap into my HTML file, I designed a basic table. To populate this table with data from an external JSON file upon clicking a button, I utilized XMLHttpRequest and JSON.parse successfully. However, I encountered difficulties when t ...

Error encountered while sending AJAX request with JSON data type

Is it possible to submit a Form using ajax with the jsontype? Suppose I have 5 fields in the form, where 4 of them are normal textboxes and one field contains JSON. When trying to send this data via ajax, an error is thrown. How can I resolve this issue? ...

Designing dynamic SVG elements that maintain uniform stroke widths and rounded edges

I'm currently tackling a project that involves creating SVG shapes with strokes that adjust responsively to the size of their parent container. My aim is for these shapes to consistently fill the width and height of the parent container, and I intend ...

Numerous documents within a JavaScript application

As a newcomer to JavaScript, I've been experimenting with the language to enhance my understanding. One aspect that puzzles me is how developers organize large JavaScript programs. In languages like Java, breaking down code into smaller files is commo ...

Merge information from various sources using ajax

Currently, I have a single ajax request that retrieves data from an API and uses it to generate a table. Now, I'm looking to modify the code so that it can retrieve data from two different URLs and merge them into the same table (retTable). Below is ...

Tool to track character limits in multiple text fields

I'm facing a challenge with a form that includes 3 text areas, a copy button, and a reset button. My goal is to concatenate all the characters in the text areas to get a sum which will be displayed next to the copy/reset button. The character limit is ...

React date format error: RangeError - Time value is invalid

I'm utilizing a date in my React app using the following code: const messageDate = new Date(Date.parse(createdDate)) const options = { month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' } as const ...

React Virtualized - Blank screen issue occurring because of continuous scrolling through a large list of ITSM items

I am currently working on a lengthy list of items and utilizing the react-virtualized library for this purpose. However, I have encountered an issue that needs addressing. https://i.stack.imgur.com/ROdjp.gif Upon attempting to scroll down for 2 seconds, ...

Perform batch updates on multiple documents using MongoDB

How can I efficiently update multiple documents in MongoDB by iterating through an array of objects and then returning the modified documents in the response? Be sure to refer to the code comments for guidance .put(function (req, res) { var data = r ...

"Utilizing Google Tag Manager to trigger events and push them to the data layer

My goal with this code is to trigger an event in the data layer through Google Tag Manager whenever a user hovers over a specific area on the website for at least 1 second. The challenge I'm facing is that I have 8 other areas on the site using the sa ...

Quickly remove items from a list without any keywords from the given keywords list

This spreadsheet contains two sheets named "RemoveRecords" and "KeywordsList". I need to use app scripts to remove any records that are not included in the "KeywordsList" sheet. This should be done by searching through the "ArticleLink" column. Although ...

Retrieving chosen items from NextUI-Table

I am completely new to JavaScript and NextUI. My usual work involves C# and DotNET. I have a requirement to create a table with selectable items, and when a button is clicked, all the selected items should be passed to a function on the server that accepts ...

Comparing the efficiency of using arrays versus mapping to an object and accessing data in JavaScript

When considering the basics of computer science, it is understood that searching an unsorted list typically occurs in O(n) time, while direct access to an element in an array happens in O(1) time for HashMaps. So, which approach yields better performance: ...

What steps do I need to take to ensure my TypeScript module in npm can be easily used in a

I recently developed a module that captures keypressed input on a document to detect events from a physical barcode reader acting as a keyboard. You can find the source code here: https://github.com/tii-bruno/physical-barcode-reader-observer The npm mod ...