Now with your code it's clear! Let's have a look at it
var chat = {
users: [
{
username: "test"
},
{
username: "test1"
}
]
},
// creating reference from save to chat.users
save = chat.users,
i = 0;
if (chat.users[i + 1]) {
// should be chat.users[1].username ("test1")
console.log("1: " + chat.users[i + 1].username); // output "test1"
}
if (save[i + 1]) {
// should be save[1].username ("test1")
console.log("2: " + save[i + 1].username); // output "test1"
}
/*
* creating reference
* so chat.users[i + 1] is now save[i] ({ username: "test" })
* and because save is reference of chat.users, save[i + 1] is now also now save[i] ({ username: "test" })
*/
chat.users[i + 1] = save[i];
if (chat.users[i + 1]) {
// should be chat.users[1].username ("test")
console.log("3: " + chat.users[i + 1].username); // output "test"
}
if (save[i + 1]) {
// should be chat.users[0].username ("test")
console.log("4: " + save[i].username); // output "test"
}
What?
Let me explain it to you again. For example you got this:
var a = [1, 2];
Now you write this:
var b = a;
Maybe you wanted to copy a to b but you ONLY created a reference!
So have a look at this:
console.log(a, b);
//=> [1, 2] [1, 2]
a[0] = 3;
console.log(a, b);
//=> [3, 2] [3, 2]
b[0] = 4;
console.log(a, b);
//=> [4, 2] [4, 2]
So if you change one value of the object or array it'll be changed for the other one too because it's only a reference and they both got the same memory address.
If you really Want to clone/copy the object/array then have a look at this question.