0

I want to change the value of the properties of a global object using a function with a parameter, but it doesn't work.

I tried to change the values โ€‹โ€‹of a property on a global object using a function with a parameter. Here:

Example-1:

 let store = {
 name: 'London',
 country: 'GB',
 feels Like: 0,
 temp: 0
 main: 0
 description: 0
 icon: 0
}

const handleInput = (varStore) => {
 varStore = {
  ...varStore,
  name: 'LA',
 }
console.log(varStore.name)//LA
}

handleInput(store)
console.log(store.name) // London

In example 1, when using the store argument to the handleInput function, the store object does not change the value of the name property in the global scope, but inside the function it does

In example 2, if I change the varStore parameter inside the function to the store variable, then everything happens the other way around

Example-2:

let store = {
 name: 'London',
 country: 'GB',
 feels Like: 0,
 temp: 0
 main: 0
 description: 0
 icon: 0
}

const handleInput = (varStore) => {
 store={
  ...varStore,
  name: 'LA',
 }
 console.log(varStore.name) // London
}

handleInput(store)
console.log(store.name) // LA

Why is that?

  • In (1) you're creating a new object with the new property - so the existing object - the `store` that exists outside - is unchanged. In (2) you're reassigning the `store` identifier outside, but the object passed into the function (the original object) is still unchanged. To mutate, you must do `store.name = 'LA'` or `varStore.name = 'LA'` โ€“ CertainPerformance Nov 26 '22 at 17:52

0 Answers0