Passing function parameters by value in JavaScript

Dealing with value and reference

This method is functional:

var temp = ['aaa','bbb'];
var b = [];
b[1] = { text: temp[1], onclick: function(){alert(temp[1])}}; // aaa on clock
b[0] = { text: temp[0], onclick: function(){alert(temp[0])}}; // bbb on clock

[0] // aaa on click
[1] // bbb on click

On the other hand, this approach does not work as expected:

var temp = ['aaa','bbb'];
var b = [];
for (i=0;i<2;i++)
{
    b[i] = { text: temp[i], onclick: function(){alert(temp[i])}};
}

[0] // bbb on click
[1] // bbb on click

Is there a possible solution to this issue?

Answer №1

Oh no, the closure issue strikes once more! The problem lies in the fact that a function defined within a loop only recognizes the variable named i ('closures' around it) but doesn't know the exact value of i at that specific moment of definition. If you search for the closure issue, you'll come across many similar occurrences here on SO. They all share a common thread: a function is defined (as an event handler or timeout callback) within a loop, and that function somehow interacts with the loop variable (or a value derived from it).

An effective solution to this issue involves explicitly localizing the loop variable for the function. Here's an example:

b[i] = (function(i) {
    return { text: temp[i], onclick: function(){alert(temp[i])}};
})(i);

Explanation: during each iteration of the loop, you create and immediately execute a function that takes the current value of i as an argument. Consequently, the function it generates (as an onclick handler, in this scenario) no longer operates on the 'closured' i but instead uses a localized one.

Wrapping a function definition within another function serves as a general remedy for such issues. However, in this particular case, there may be room for optimization:

b[i] = (function(tempVal) {
    return { text: tempVal, onclick: function(){alert(tempVal)}};
})(temp[i]);

... since you solely manipulate the temp[i] value here, without any reliance on i itself.

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

Next.js is having trouble identifying the module '@types/react'

Every time I attempt to launch my Next.js app using npm run dev, an error notification pops up indicating that the necessary packages for running Next with Typescript are missing: To resolve this issue, kindly install @types/react by executing: np ...

Guide for eliminating a specific row from a list in AngularJS

Despite my thorough search, I couldn't find a solution to my problem of deleting the CORRECT row from the list. Let's say I have the following array: $scope.rows = [{ "ID": 12, "customer": "abc", "image": "abc.jpg", },{ ...

Creating a zip file that stores an array of bytes and then accessing the data within

Excuse my English. I require a byte array (achieved through zip), without the use of files, channels or buffers. Following this, I need to extract (unzip) this array into another array. I attempted the following approach but encountered issues: public c ...

JavaScript event in Chrome extension triggers a browser notification and allows for modification using a specific method

I am currently developing a Chrome extension that is designed to take specific actions when system notifications appear, with the main goal being to close them automatically. One example of such a notification is the "Restore pages?" prompt: https://i.sta ...

Service Worker unable to register due to an unsupported MIME type ('text/html') declared

Working on a project using create-react-app along with an express server. The pre-configured ServiceWorker in create-react-app is set up to cache local assets (https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README ...

Transforming a C-style string into an array format

char str1 [] = "{ \'Carl Carol von Weber\', \'weber\', 8 }{ \' Carol von Carl Weber \', \'weber\', 1 }\n" "{ \'Carl Weber Carol von&bso ...

The Phalcon Volt Array consists solely of strings

I am currently working on implementing a custom Phalcon volt template and I encountered an issue with a helper function. The helper function is designed to accept an array as input, however, when the array is passed to the helper, it is treated as a string ...

What is the best way to set all "read" values to true for the child messages within the Firebase database?

https://i.sstatic.net/oukpl.png How can I set the read property of all children of a message to true in JavaScript with a single command? I attempted using let ref = yield firebase.database().ref(groups/${groupId}/messages).update({read:true}) but it did ...

What is the best way to update a form after it has been submitted?

i have a form that looks like this <form id="abc"> <div> <select > <option id= "1"> ha1 </option> <option id= "1"> ha2 </option> <option id= "1"> ha3 </option> <option id= "1"> ha4 </option> ...

Preventing the Spread of JavaScript Promises

Consider a scenario where there is a promise chain structured as shown below. The goal is to prevent func3 or func4 from being called when func2 is invoked. AsyncFunction() .then(func1, func2) .then(func3, func4) Currently, throwing an error in func2 res ...

Create a new object with the first two keys of the array of objects as keys for the new object, and the third key as an array within that

I am dealing with JSON data from a csv file and need to extract Test and Result values for each object. My goal is to create an indicator array based on the matching Test and Result in each object. [{ "Test": "GGT", "Result ...

HTML code displaying a fixed message at the top of the webpage

I'm working on a web page that has a lot of content. I need to have a message always visible at the bottom of the browser window, even when scrolling. Can anyone help me achieve this using simple CSS, HTML, jQuery, or PHP? Thanks! ...

Cannot bind rvalue reference to temporary constant array

Below is the test program currently in question: #include <iostream> #include <type_traits> #include <utility> template<typename Ty, std::size_t N> void foo(Ty (&&)[N]) { std::cout << "Ty (&&)[" << ...

Determine the presence of an image by using a wildcard in the URL

I need to show an image, and if it doesn't exist I want to display a default image. The challenge is that the image can come with any extension. Can someone suggest how I can modify the $.get() function in the code snippet below to make it search for ...

Best JavaScript approach for discovering time-dependent occurrences

In my Javascript code, I am working with an array of objects that have event start and end times stored as milliseconds. The current search algorithm in our codebase loops through the array until finding an event that contains a specific moment: // Lookin ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

Issue: Error encountered while trying to use the removeAttribute() function in Selenium and Java: missing closing parenthesis after argument list

WebElement removeReadOnly=driver.findElement(By.xpath("//input[@id='mat-input-0']")); js.executeScript("document.getElementBypath('//input[@id='mat-input-0']').removeAttribute('readonly');",&quo ...

How can I locate the element immediately preceding $(this)?

Struggling to retrieve the value of the $(.subname) when the .bigadminbutton is clicked and calling the updateSub() function. I have tried various methods like prev, sibling, parent, children, find, but none seem to work. This minor task is taking up too ...

JavaScript can be used to create dynamic frames within a

Can anyone help identify the issue in my code? frame 1 <script type="text/javascript"> var Clicks = 0 ; function AddClick(){ Clicks = Clicks + 1; document.getElementById('CountedClicks').innerHTML = Clicks ; } localStorage.setItem(' ...

The initial attempt to fetch a value using jQuery returned as undefined

When using jQuery to retrieve each message ID, I am facing an issue where the first instance of the message that the user has shows up as undefined. However, for all subsequent messages, it works perfectly fine. var mssg_id = $(this).find('input[name= ...