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

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

Implementing Kendo UI dataSource to interact with a PHP function

Greetings Everyone, I have a category.php file within my code that handles CRUD functions. However, I am unsure how to call these functions in the Kendo UI dataSource/transport. Previously, I had separated the PHP files, but now I want to consolidate them ...

How can I programmatically trigger the opening of a Material-UI Accordion in ReactJS?

All of the Accordions are assigned unique IDs: const CategoryDisplay: React.FC<Props> = (props) => { ... return ( <> <Accordion id={`category-${accordion.id}`}/> </> ); }; export default CategoryDisplay ...

Utilizing ReactJS to retrieve configuration settings from a YAML file, similar to how it is done

Our team is currently using a full-stack multi-microservice application where the backend java components utilize the spring @value annotation to fetch configuration values from a yml file. This method has been effective and even the Java side of our UI c ...

Using Node.js, securely encode data using a private key into a base64 format that can only be decoded on the server side

Here is my specific situation: An http request arrives at the server for a login action A user token needs to be created. This token consists of a Json object composed of different fields. It is then converted to a string and encoded in Base64. const ...

JSON with a null character

Despite spending an hour searching online, I feel a bit hesitant to ask this question. Can null characters (ascii null or \0) be used within JSON? I know they are not allowed within JSON strings, but my query is whether they can be included in the bod ...

iPhone 6 (iOS) users may face compatibility issues with iframe and fancy box features

I am currently learning how to use jQuery and the fancybox library. In my Angular 1 and Ionic project, I have successfully implemented fancybox with an iframe. Everything works perfectly on browsers and Android devices, but on iOS, a loader icon appears an ...

Getting the string value from query parameters can be achieved by accessing the parameters and

Currently, I am attempting to retrieve the string value stored within a class-based object variable named question5. The way I am trying to access this variable on the front-end is shown below. axios.get("http://localhost:3001/users/questionaire/?getq ...

The Angular ViewportScroller feature appears to be malfunctioning in the latest release of Angular,

TestComponent.ts export class TestComponent implements OnInit, AfterViewInit { constructor( private scroller: ViewportScroller, ) {} scrollToAnchor() { this.scroller.scrollToAnchor('123456789'); } } HTM ...

Utilize Next.js with Axios for making an HTTP request to a Laravel Lumen endpoint, then showcase the retrieved data within the Next.js

I currently have a Next.js application that utilizes Axios to make calls to Lumen endpoints. The Axios HTTP client functions are organized in a separate folder named services/index.tsx, with sample code as follows: export const register = async (payload: a ...

What are the steps to correctly implement async await in a standard sequence?

When I press the button onPress={() => Login()} First, I need to obtain a token by using the signInWithKakao function. Secondly, right after acquiring the token, if it is available, I want to dispatch the profile using the kakaoprofile function. Howev ...

Issue encountered while retrieving JSON data from Github

I am currently using d3.json to retrieve a JSON link from the Enterprise GitHub (within the same repository/folder as the JavaScript file). d3.json("https://raw.github.exampleEnterprise.com/path/to/repo/data.json?token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ...

Are there numerous instances of jQuery references both preceding and following the use of '$.noConflict'?

Managing a large project with thousands of PHP files can be challenging, especially when dealing with conflicting jQuery references that hinder the implementation of a desired plugin. Consider this scenario: <html> <head> ...

Interactive element for initiating a HTTP request to NodeJS/Express server to trigger a specific function

I currently have a frontend button implemented using nodejs and express for my server-side backend. The button is supposed to trigger a function that controls the Philips Hue API on the backend via an HTTP request. I have experimented with various approac ...

The variable declared in the useState hook is not being properly updated within the callback function

const ModifiedTweet = ({ tweet, checkedList, setCheckedList }) => { const [isChecked, setChecked] = useState(false); useEffect(() => { if (checkedList.length === 0) { setChecked(false); } }, [checkedList, isChecked]); return ( ...

Ways to verify if a user is authenticated without relying on request.session

I am currently developing a web application using Express, Docker, and following a Three-layered architecture. In my app, I store user login information in a session and have blogposts as a key resource. To retrieve the blogpostId from the database in the ...

Tips for preventing repetition of code in multiple entry points in Rollup

My goal is to use rollup to process a group of input files and generate multiple output files in the dist directory that all have some common code shared between them. Below is my current rollup configuration: import path from 'path'; import pat ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

Enabling the use of jQuery with Angular instead of JQLite

According to the angular DOCS, if jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to AngularJS's built-in subset of jQuery, known as "jQuery lite" or jqLite. In an attemp ...

Successfully resolved: Inability to dynamically adjust button color according to its state

Currently I am working on a feature where a button changes color when it is disabled, but also has a custom color when enabled. Here is the code snippet I am using: Despite setting blue text for the button, it remains blue even after becoming disabled. Ho ...