0

I've run in to a situation that can't really explain how is this even possible.

I made a plunker for a demo.

THE CODE:

angular.module('test', []).controller('TestController', function($scope) {

/*
  DEFAULT CONST VARIABLE
*/
const _DEFAULT = {
  items: [],
  name: 'Test',
  selected: null
};

/*
  TEST_CASE SCOPE VARIABLE
*/
$scope.test_case = _DEFAULT;

console.log('ON INIT DEFAULT: ', _DEFAULT);

/*
  FUNCTION
*/
$scope.clicked = () => {
  // SET TEST_CASE.SELECTED = 1
  $scope.test_case.selected = 1;

  // SHOW UPDATED TEST_CASE AND _DEFAULT VARIABLE
  console.log($scope.test_case, _DEFAULT);
};

});

When button is clicked (check demo) we change data only in $scope.test_case so HOW is it possible that const variable _DEFAULT has the same data as $scope.test_case when _DEFAULT has never been touched or changed?

That should be impossible or am I missing something?

Vizjerei
  • 1,000
  • 8
  • 15
  • Because `$scope.test_case` is *the same* as `_DEFAULT`? – Bergi Jun 26 '17 at 17:35
  • How is it the same? If it's the same then how can you make a variable that won't be updated but is assigned? Just like _DEFAULT I don't wan't it updated. I wanted $scope.test_case updated. GOt both updated instead. – Vizjerei Jun 26 '17 at 17:38
  • 1
    There is no "both objects", there is only one object referenced twice. If you want an independent second one, you have to explicitly clone it - see the duplicate. – Bergi Jun 26 '17 at 17:55

1 Answers1

1

This is by design:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g. its parameters) can be altered.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

The const keyword in this context will prevent the variable, _DEFAULT from being assigned a new value, but it will not prevent the value of that variable from changing.

Pop-A-Stash
  • 6,572
  • 5
  • 28
  • 54
  • But I haven't altered the _DEFAULT data in any way. The only variable that I wan't to update is $scope.test_case. – Vizjerei Jun 26 '17 at 17:41
  • 1
    @Vizjerei both `_DEFAULT` and `$scope.test_case` are pointing to the same object. You are updating this object and as such, the change is reflected in both references. – Thomas Maddocks Jun 26 '17 at 17:46
  • 1
    When you assign `$scope.test_case` to `_DEFAULT` you are assigning it by reference and not by value. If you want a copy of default, use `angular.copy(_DEFAULT)` to get a new instance of the object. – Pop-A-Stash Jun 26 '17 at 17:47
  • Thanks for the answer. Now I get it. – Vizjerei Jun 26 '17 at 17:48