Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoping of variable inside a javascript map

{charts.map( (ch, i) => {
   const tempApiDetails = {...apiDetails};
   tempApiDetails.apiOptions.params = generateParams(ch.dashBoardType, ch.reportType); 
   //above line is to generate params for API call

   <SimpleTable apiOptions={tempApiDetails} />
})}

in the above code the charts is having 3 items. but all three in the end is having the same params which is made for the last chart in the charts variable. Can somebody explain me what will be underlying principle for it?

like image 516
JIMMY JACOB Avatar asked Dec 15 '21 09:12

JIMMY JACOB


People also ask

What is the scope of JavaScript variables?

In JavaScript there are two types of scope: JavaScript has function scope: Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function.

What is global scope in JavaScript?

Global scope. JavaScript has function scope: Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function.

Can a variable have a scope inside a block?

Variables declared with the var keyword can NOT have block scope. Variables declared inside a { } block can be accessed from outside the block. Variables declared within a JavaScript function, become LOCAL to the function. They can only be accessed from within the function.

Can a variable have a local scope in C++?

A variable can also have a local scope, i.e it can only be accessed within a function. In the above program, variable a is a global variable and variable b is a local variable. The variable b can be accessed only inside the function greet. Hence, when we try to access variable b outside of the function, an error occurs.


1 Answers

This has nothing to do with scope.

tempApiDetails is a shallow copy of apiDetails.

This means the value of tempApiDetails.apiOptions is the same each time it goes around the loop.

Since it is an object, and objects are stored by reference, every time you assign to apiOptions.params you are overwriting the params of the same object.

You need to make a clone of apiOptions.

const tempApiDetails = {
    ...apiDetails,
    apiOptions: {...apiDetails.apiOptions}
};

And you can do the whole thing in one go:

const tempApiDetails = {
    ...apiDetails,
    apiOptions: {
         ...apiDetails.apiOptions,
         params: generateParams(ch.dashBoardType, ch.reportType)
    }
};

For complex data structures you might want to look at the immer library which will take care of all the cloning for you.

const tempApiDetails = produce(apiDetails, draft => {
    draft.apiOptions.params = generateParams(ch.dashBoardType, ch.reportType);
});
like image 108
Quentin Avatar answered Oct 01 '22 16:10

Quentin