Attribution operator "=" javascript

Asked

Viewed 118 times

1

I’ll tell you what:

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 "starting date" updating along with the variable "d", if I don’t increment it??????

  • 2

    This is because Javascript objects behave as a reference and not "as a value". I will try to detail an answer

1 answer

2

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

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 at position 01.
  • dataInicial at position 02.
  • dataFinal at position 03.

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

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

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 position.

  • 1

    I think you can complete your answer by indicating how to get around this problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.