2

Cannot figure out, why the object innerMain is getting smaller on every select change even though it gets redefined with object main’s structure in the beginning of the every call to the trig() function:

let innerMain = main;

var main = {
    1: 0,
    2: 0,
    3: 0,
    4: 0
  };

$('#sel').on('change', function(){
  trig($(this));
});


function trig(th = false){
  let innerMain = main;

  delete innerMain[th.val()];
  console.log(innerMain);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</select>
<div id="result"></div>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
mr.work
  • 173
  • 10
  • Do you expect `let innerMain = main;` to create a _copy_ of `main`? – Sebastian Simon Sep 25 '19 at 13:04
  • 2
    Possible duplicate of [Modifying a copy of a JavaScript object is causing the original object to change](https://stackoverflow.com/questions/29050004/modifying-a-copy-of-a-javascript-object-is-causing-the-original-object-to-change) – Sebastian Simon Sep 25 '19 at 13:04
  • @SebastianSimon, yes kinda :/ – mr.work Sep 25 '19 at 13:05
  • Simple answer is there is only one object....the variables are *references* to the exact same object. `innerMain = main` *does not* make a copy – charlietfl Sep 25 '19 at 13:06
  • 2
    Try `let innerMain = Object.assign({}, main);` to create a quick copy of the object. Note that this works because all your keys in the original object are not objects themselves. – somethinghere Sep 25 '19 at 13:10
  • @mr.work Why not just declare `main` inside of `trig`? Do you actually need it outside? – Marie Sep 25 '19 at 13:35

1 Answers1

3

It happens cuz you create new variable (innerMain) with reference to old (main) variable, and every time when you call delete, you call it for old variable (main)

So, you have only one variable and you modify it.

You should create new variable without reference. How it works, you can read on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Objects https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

It works:

var main = {
    1: 0,
    2: 0,
    3: 0,
    4: 0
  };

$('#sel').on('change', function(){
  trig($(this));
});


function trig(th = false){
  let innerMain = Object.assign({}, main);

  delete innerMain[th.val()];
  console.log(innerMain);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</select>
<div id="result"></div>
Artem Getmanskiy
  • 193
  • 2
  • 16