BTW, there is only 1 box variable, and it's not copying the object. You can copy the value of a primitive (string, number, boolean, null, undefined, symbol).
// Copies value
var foo = "eggs";
var bar = foo;
foo = "ham";
console.log(foo); // "ham"
console.log(bar); // "eggs"
For everything else, it's not that straightforward. Try searching for pass by value and by reference as it can be hard to explain.
Variables do not store the value of an object, they just hold a reference to an object's location in memory, kind of like a home address. And just like your home address, it can be passed around and be used by more than 1 person.
Notice how alpha and bravo appear to have the same value, but they are not equal. On the other hand, alpha and charlie are equal even though I changed the value of the msg property. That's because they are pointing to the same object.
var alpha = { msg: "Hello World!" };
var bravo = { msg: "Hello World!" };
console.log(alpha === bravo); // false
// Copies reference
var charlie = alpha;
charlie.msg = 123;
console.log(alpha === charlie); // true
console.log(alpha.msg); // 123
console.log(charlie.msg); // 123
And about there only being 1 box variable, that's because of something called hoisting. There is no difference between these two loops. All var declarations are moved to the top of their scope by the JavaScript compiler, so the first loop will end up looking just like the second loop.
for (var i = 0; i < 2; i++) {
var box = boxes[i];
}
var box;
for (var i = 0; i < 2; i++) {
box = boxes[i];
}
That's why this crazy looking code is totally valid. The num variable gets moved to the top.
num = 8;
num += 4;
var num;
console.log(num); // => 12