I am currently learning about objects in javascript.
I have encountered behaviour I didn't expect and I want to confirm if I am seeing what I should be seeing or if I have made a mistake somewhere.
var a = 1;
var b = a;
b++;
console.log(a); // 1 (As expected)
console.log(b); // 2
var a = 'string';
var b = a;
b += 'ier';
console.log(a); // string (As expected)
console.log(b); // stringier
var a = {};
var b = a;
b['testValue'] = 'test';
console.log(a); // {testValue = 'test'} (Wait... what?!)
console.log(b); // {testValue = 'test'}
Added:
I've just tried the same experiment with an array and I see the array is exhibiting the same behaviour as the object (perhaps to be expected, given that arrays are objects in Javascript)
var a = [];
var b = a;
b[0] = 'test';
console.log(a); // ['test'] (Hmmm... again!)
console.log(b); // ['test']
Why are the object and the array behaving differently from the number and the string?
Why is var b
only referencing var a
rather than duplicating it?