Assignment Operator "=" javascript

1

I do the following:

var d = new Date();
var dataInicial = new Date(2017, 5, 1);
var dataFinal = new Date(2017, 5, 20);

var percorreDatas = function(){
  d = dataInicial;
  while(d <= dataFinal){
    d.setDate(d.getDate()+1);
    console.log("d", d);
    console.log("dataInicial", dataInicial);
  }
}

percorreDatas();

Why is the variable "initial_database" updating along with the variable "d", if I do not increment it ??????

    
asked by anonymous 26.05.2017 / 02:01

1 answer

2

As @Guilhere Nascimento commented, this is because objects in javaScript are mere references to a position in memory.

var d = new Date();
var dataInicial = new Date(2017, 5, 1);
var dataFinal = new Date(2017, 5, 20);

For example, let's say the variable

  • d is stored in memory position 01.
  • dataInicial in position 02.
  • dataFinal at position 03.

When you set d = dataInicial , the variable d no longer points to memory position 01, but to position 02, which is the position occupied by the dataInicial variable.

When you do d.setDate(d.getDate()+1) , strange as it may seem, you are updating position 02 from memory, not position 01, which is where the d variable was initially allocated.

At this point, there are two variables, d and dataInicial , which, although they have different names, will always have the same value, since both point to the same memory location.     

26.05.2017 / 02:46