Linked Questions

Popular Questions

Firstly know that I am pretty new to Javascript. I am wondering why when I run this script I can successfully set newVar to my modified baseVar, but if I reuse the same baseVar variable it will also change newVar, despite not changing newVar iteself.

var newVar = 0;
var baseVar = {number: 0,};

function generateNumber() {
  var number = Math.round(Math.random() * 50);
  baseVar.number = number;
  console.log(baseVar);
}

generateNumber();
newVar = baseVar;
console.log(newVar);
generateNumber();
console.log(newVar);

If I run my function twice, the first time number is 2, and the second time number is 37, I expect my output to read...

[object Object] {
  number: 2
}
[object Object] {
  number: 2
}
[object Object] {
  number: 37
}
[object Object] {
  number: 2
}

But what I get is...

[object Object] {
  number: 2
}
[object Object] {
  number: 2
}
[object Object] {
  number: 37
}
[object Object] {
  number: 37
}

Related Questions