Modify variables in the child function to be utilized in the parent function

I need to create a scenario where a variable defined in a parent function is modified within a child function and then returned back to the parent as an updated variable.

Here is the code I have attempted:

let value = 20;
console.log(value); // Output: 20 (as expected)
testValue(value);
console.log(value); // I expect this to be 30

function testValue(value) {
    value = 30;
}

Answer №1

Within this discussion, we find several insightful perspectives worth exploring. I would like to contribute by presenting an approach that could be effective depending on how one defines the terms "parent function" and "child function."

In cases where the "child function" is contained within the "parent function," it is possible for the outer function's variable scope to remain active within the inner function, provided there are no conflicting variables declared within the inner function.

For instance, eliminating the parameter from the function in your example can yield the desired outcome. The mention of wuzi within testWuzi transforms into a closure, linking back to the wuzi variable defined outside that function.

let wuzi = 20;
console.log(wuzi); //20 as expected
testWuzi(wuzi);
console.log(wuzi); //30

function testWuzi() {
    wuzi = 30;
}

Answer №2

When a variable is passed into a function, it is not possible for the function to directly modify the variable itself. The value of the variable is what gets passed in, not the variable itself. Primitive types like 20 are considered "immutable," meaning they cannot be changed.

One solution is to pass in an object instead of a primitive type, as objects can be modified:

let wuzi = { value: 20 };
console.log(wuzi.value); //Outputs 20
testWuzi(wuzi);
console.log(wuzi.value); //I want this to be 30

function testWuzi(wuzi) {
    wuzi.value = 30;
}

Another approach is to have the function return an updated value rather than modifying the original one. This is preferred by some because it avoids potential "side effects":

let wuzi = 20;
console.log(wuzi); //Outputs 20
wuzi = testWuzi(wuzi);
console.log(wuzi); //I want this to be 30

function testWuzi(wuzi) {
    return wuzi + 10;
}

Answer №3

The reason behind this is because it is passing by value. To achieve the expected outcome, you need to change it to pass by reference

An alternative is to store it in an array

let number = [20];
console.log(number[0]); //20 as expected
testNumber(number);
console.log(number[0]); //I want this to be 30

function testNumber(number) {
    number[0] = 30;
}

Another choice is to store it in an Object

let number = {val:20};
console.log(number.val); //20 as expected
testNumber(number);
console.log(number.val); //I want this to be 30

function testNumber(number) {
    number.val = 30;
}

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

Gather information from various entities using JavaScript

I am looking to parse data from an Object and save them in an array. Specifically, I aim to extract all the US shoe sizes and compile them into an array. However, when utilizing the filter method, it only retrieves the first item with the "us" value. { ...

What is the Best Way to Enable Tooltips to Function from External Elements?

I am currently designing a map that features points with tooltips. When hovered over, the tooltips function correctly. I am interested in exploring the possibility of making the tooltips interact with an external navigation bar. My goal is to have specifi ...

The 'export '__platform_browser_private__' could not be located within the '@angular/platform-browser' module

I have encountered an issue while developing an angular application. Upon running ng serve, I am receiving the following error in ERROR in ./node_modules/@angular/http/src/backends/xhr_backend.js 204:40-68: "export 'platform_browser_private' w ...

Is placing JavaScript on the lowest layer the best approach?

I'm facing a unique situation that I haven't encountered before and am unsure of how to address it. My website has a fixed top header and footer. On the left side, there is a Google Adsense ad in JavaScript. When scrolling down, the top header s ...

Efficiently select multiple classes in Material UI with just one target

I'm currently working with Material UI and I want to update the color of my icon class when the active class is triggered by react-router-dom's NavLink Here is my code: import React from "react"; import { makeStyles } from "@mater ...

Transforming CSV files into JSON format using d3.js

I'm encountering an issue when attempting to convert CSV to JSON. The following is the snippet of code I am using for the conversion: d3.csv("http://localhost:8080/Sample/flight.csv", function(flights) { //alert(flights); ...

Redirecting script upon successful connection detection

I have created a script that checks for internet connectivity using an image, and redirects if internet is available. However, the issue is that it caches the images, leading to attempts to load them even when offline. Is there a different approach I can ...

Updating to the latest version of Next.js will result in a modification of the API path

I recently updated my app to the latest version of nextjs (13.1.6) and encountered a problem where all my requests are now failing. It seems that the URL I specified in the request creator, based on the ENV value, is being overwritten. .env file CONST NEXT ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured: [{ "uniqueID": "CHECKOUT_IE01", "orderID": "4001820182", "date": "06-02-2019 16:55:32.32 ...

Dynamically load npm modules in Webpack using variables for the require statement

Is there a way to dynamically require an NPM module using a variable? Below is the sample code I've been trying, everything seems to be working fine except for importing NPM modules dynamically. const firstModule = 'my-npm-module'; const s ...

What is the best way to bring a JavaScript file from the source file into an index.html document

I am currently in the process of developing a system using React, and as someone new to the framework, I have encountered an issue. I need to include a JavaScript file in my index.html that is located within the src folder. This js file is essential for th ...

Unable to locate the tag using .find() function following the use of .attr() method

I am currently utilizing jQuery in conjunction with node-horseman to interact with a specific page. My approach involves referencing the page's data-id attribute, which I then pass to my application to search for the li element containing this attribu ...

Is there a way to activate the autoplay feature for this?

I'm really new to Jquery and most of this code isn't mine, I'm just using it as a learning tool for creating sliders. If someone could give me some guidance on how to make this slider work automatically when the page loads, that would be gre ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

Issue: Invalid element type - Error message displayed when attempting to show the Edit button

I am currently learning about React and trying to implement an edit button next to the rows for editing data in the database. However, I keep encountering this specific error message: Error: Element type is invalid: expected a string (for built-in compone ...

inside the connect module, the res._renderHeaders function is located

Currently, I am delving into the patch.js file within the connect module. In it, I found some intriguing code snippets: var http = require('http') , res = http.ServerResponse.prototype , setHeader = res.setHeader , _renderHeaders = res._re ...

Utilize the context API to efficiently share information from the parent to both its children and sibling children

I'm currently working on displaying fetched data in a child component using the context API, but encountering an error in the browser: TypeError: render is not a function The above error occurred in the component: in AppDataList (at App.j ...

Replicate styling while copying CodeMirror code

Is there a way to maintain the styling and formatting of javascript code when copying from CodeMirror? Whenever I try to copy and paste from the CodeMirror editor, the coloring and style are lost, with the content pasted as text/plain. How can I preserve ...

The ternary operator is malfunctioning when it comes to the condition

I've encountered an issue while trying to integrate a custom MUI button into my project. My goal is to have the button enabled only when 2 specific objects are not empty, otherwise it should remain disabled. Despite my efforts, the code I've writ ...