What is difference between assigning value to variable and storing value into variable - javascript

I was reading a book about object oriented javascript and I found this:
Reference types do not store the object directly into the variable to which it is assigned, so the
object variable in this example doesn’t actually contain the object instance. Instead, it holds
a pointer (or reference) to the location in memory where the object exists. This is the primary
difference between objects and primitive values, as the primitive is stored directly in the variable.
My question is
what is the meaning of this ?
"Reference types do not store the object directly into the variable to which it is assigned, so the object variable in this example doesn’t actually contain the object instance." ??

In the image you provided you can see
var object1 = new Object();
var object2 = object1;
In this case, you have two variables that both store a reference (think of a pointer) to another place in your memory. In this place the object is stored. If you change your object via one of the references, and access it via the other one you will see it has changed.
object1.someVariable = 'asdf';
object2.someVariable = 'newValue';
console.log(object1.someVariable); // will give 'newValue'
console.log(object2.someVariable); // will also give 'newValue'
If you have scalar values, they will not store references, they will store the value itself.
Think of another example:
var primitiveString = 'asdf';
var anotherPrimitiveString = primitiveString;
Since both store the value it self, you can change one of the two strings, but the other one will still contain asdf, since they do not reference something.
anotherPrimitiveString = 'newValue';
console.log(primitiveString); // will give 'asdf'
console.log(anotherPrimitiveString); // will give 'newValue'
Here you have a jsfiddle with the explained example.

It could be clearer with an example:
var obj1 = { name: "John" };
var obj2 = obj1;
obj1 and obj2 point to the same location in memory.
It can be proved by changing name property:
obj2.name = "Bob";
console.log(obj1.name); // "Bob"
Another behaviour with primitives:
var string1 = 'string';
var string2 = string1;
string1 and string2 point to different locations in memory. So changing string2 won't affect string1
string2 = 'new string';
console.log(string1); // 'string'

You have a house. You = variable. House = value. Now, you have to prove you own that house. You get a paper, stating that you are the owner.
When you go around, you don't have to carry your house. You can just show people the paper.
House = heavy, hard to move.
Paper = small, light, easy to move.
That paper does what storing a reference does. It does not actually hold the real object, but it tells the rest of the system where it is.

In computer science in general there is two type of variables types, pointers and values.
Pointers don't hold anything but an address so the computer can find where the real value is stored, while values store the real data.
The power of pointers is you can define one value and have multiple pointers use that same value. This is a huge gain in memory management and bidirectional communication from one section of code and another.
This is an example of a pointer in javascript.
var foo = { value : 1};
var goo = foo;
goo.value = 4;
//now both goo.value and foo.value are both 4.
A value is something like this.
var foo = 2;
var goo = foo;
goo = 4;
//now foo is 2 and goo is 4.

Object1 refers to some memory location (for example 2002). Object2 is also refered to the same memory location but by referring Object1.

In js it is best to think that variables are pointers to objects & when assign directly to a variable you are not modifying any object , but pointing your variable to an object.
Let us take this example
var a= b ={}
So here a & b are pointer to same object.
Now set a.someProp = 'value'
it sets b.someProp as well since a & b point to same object
Where as storing a value in a variable is called variable initialization

Related

In Javascript, after Const array variable is declared, but each of its elements can still be modified. Any reason behind it? [duplicate]

I know that ES6 is not standardized yet, but a lot of browsers currently support const keyword in JS.
In spec, it is written that:
The value of a constant cannot change through re-assignment, and a
constant cannot be re-declared. Because of this, although it is
possible to declare a constant without initializing it, it would be
useless to do so.
and when I do something like this:
const xxx = 6;
xxx = 999;
xxx++;
const yyy = [];
yyy = 'string';
yyy = [15, 'a'];
I see that everything is ok: xxx is still 6 and yyy is [].
But if I do yyy.push(6); yyy.push(1); , my constant array has been changed. Right now it is [6, 1] and by the way I still can not change it with yyy = 1;.
Is this a bug, or am I missing something? I tried it in the latest chrome and FF29
The documentation states:
...constant cannot change through re-assignment
...constant cannot be re-declared
When you're adding to an array or object you're not re-assigning or re-declaring the constant, it's already declared and assigned, you're just adding to the "list" that the constant points to.
So this works fine:
const x = {};
x.foo = 'bar';
console.log(x); // {foo : 'bar'}
x.foo = 'bar2';
console.log(x); // {foo : 'bar2'}
and this:
const y = [];
y.push('foo');
console.log(y); // ['foo']
y.unshift("foo2");
console.log(y); // ['foo2', 'foo']
y.pop();
console.log(y); // ['foo2']
but neither of these:
const x = {};
x = {foo: 'bar'}; // error - re-assigning
const y = ['foo'];
const y = ['bar']; // error - re-declaring
const foo = 'bar';
foo = 'bar2'; // error - can not re-assign
var foo = 'bar3'; // error - already declared
function foo() {}; // error - already declared
This happens because your constant is actually storing a reference to the array. When you join something into your array you are not modifying your constant value, but the array it points to. The same would happen if you assigned an object to a constant and tried to modify any property of it.
If you want to freeze an array or object so it can't be modified, you can use the Object.freeze method, which is already part of ECMAScript 5.
const x = Object.freeze(['a'])
x.push('b')
console.log(x) // ["a"]
Came through this article while searching on why I was able to update an Object even after defining it as const. So the point here is that it is not the Object directly but the attributes it contains which can be updated.
For example, my Object looks like:
const number = {
id:5,
name:'Bob'
};
The above answers correctly pointed out that it's the Object which is const and not its attribute. Hence, I will be able to update the id or name by doing:
number.name = 'John';
But, I will not be able to update the Object itself like:
number = {
id:5,
name:'John'
};
TypeError: Assignment to constant variable.
This is consistent behavior with every programming language I can think of.
Consider C - arrays are just glorified pointers. A constant array only means that the value of the pointer will not change - but in fact the data contained at that address is free to.
In javascript, you are allowed to call methods of constant objects (of course - otherwise constant objects would not serve much purpose!) These methods might have the side effect of modifying the object. Since arrays in javascript are objects, this behavior applies to them as well.
All you are assured of is that the constant will always point to the same object. The properties of the object itself are free to change.
The keyword const is a little misleading.
It does not define a constant value. It defines a constant reference to a value.
Because of this you can NOT:
Reassign a constant value
Reassign a constant array
Reassign a constant object
But you CAN:
Change a constant array
Change a constant object
I think this would give you more clarity on the issue : https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0 .
Basically it boils down to the const always pointing to the same address in memory. You can change the value stored in that address but cannot change the address the const is pointing too.
The definition of const you mentioned will hold true when the const is pointing to an address that holds a primitive value . This is because you cannot assign a value to this const without changing its address (because this is how assigning primitive values work) and changing the address of a const is not allowed.
Where as if the const is pointing to non-primitive value , it is possible to edit the value of the address.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its parameters) can be altered.
In addition, an also important note:
Global constants do not become properties of the window object ...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
The value of a const can't be changed through reassignment, and it can't be redeclared.
const testData = { name:"Sandeep",lastName:"Mukherjee",company:"XYZ"}
First case
testData = {name:"hello"}
console.log(testData);//throws an Error:Assignment to constant variable
Here we are reassigning testData again
Second case
const testData = {name:"Sandeep",lastName:"Mukherjee",company:"ABC"}
console.log(testData); //throws an Error: Identifier 'testData' has already been declared
Here we are redeclaring testData again
When a variable is declared using const it means it points to some memory location the
behaviour of const is we can manipulate the value stored in that memory location but not
the memory location,when we reassign/redeclare the const variable it
does not allow to change the memory location
We can change the value of a specific key
testData.company = "Google"
console.log(testData);
//{ name: 'Sandeep', lastName: 'Mukherjee', company: 'Google' }
We can add any new key value pair to it
testData.homeTown = "NewYork"
console.log(testData)
//{name: 'Sandeep',lastName:'Mukherjee',company:'Google',homeTown: 'NewYork'}
Because in const you can change the values of an object, so the object does not actually store the assignment data but instead, it points to it.
so there is a difference between primitives and objects in Javascript.
const variable stores the address (memory address such as 0xFF2DFC) that is constant.
The constant is NOT the content at the memory.
constant is memory address ONLY
Thank you for reading.
const MY_OBJECT = {'key': 'value'};
// Attempting to overwrite the object throws an error
// Uncaught TypeError: Assignment to constant variable.
MY_OBJECT = {'OTHER_KEY': 'value'};
// However, object keys are not protected,
// so the following statement is executed without problem
MY_OBJECT.key = 'otherValue';
// Use Object.freeze() to make object immutable
// The same applies to arrays
const MY_ARRAY = [];
// It's possible to push items into the array
MY_ARRAY.push('A'); // ["A"]
// However, assigning a new array to the variable throws an error
// Uncaught TypeError: Assignment to constant variable.
MY_ARRAY = ['B'];
In your constant is saved not the object, but link to the object.
You can't change this link, because it is constant.
But object you can change.

Setting a variable equal to another variable [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 2 years ago.
I have a few questions about setting a variable equal to another variable in JavaScript.
Let's say we create an object, a and set b = a.
var a = {
fname: "Jon",
lname: "Smith",
age: 50
}
var b = a;
I understand that if we change one of a's properties b will also be changed because when we set b = a we don't clone a's data, but rather create a reference to a's data. For example if we set a.fname = "Sarah", the new value of b.fname will be "Sarah".
If we try to "clear" a though by setting a = {}, object b will remain unchanged. I don't understand why manipulating an object in this way produces a different result than in the 1st example.
Also I have a question about the following scenario.
var x = 10;
var z = x;
If we then set x = 20, the value of z remains unchanged. Based on the behavior described in my 1st question, one would think that the new value of z would reflect the new value of x. Could someone please explain what I am missing here?
Thank You!
The really short answer to both your questions is that when you make one variable equal to another, a COPY of what's in the first variable is made and stored in the second variable - there is no linkage between the two variables.
But, read on for more details and why it can seem like there is a link in some cases...
JavaScript, like many languages, divides data into two broad categories: value types and reference types. JavaScript value types are its primitives:
string
number
boolean
null
undefined
symbol
When you assign any of these types to a variable, the actual data is stored in that variable and if you set one variable equal to another, a copy (not a linkage) of the primitive is made and stored in the new variable:
var a = 10; // Store the actual number 10 in the a variable
var b = a; // Store a COPY of the actual number stored in a (10) in the b variable
a = 50; // Change the actual data stored in a to 50 (no change to b here)
console.log("a is: " + a); // 50
console.log("b is: " + b); // 10
When you work with reference types, something a little different happens. Assigning a variable to a reference type means that the variable only holds a reference to the memory location where the object is actually stored, not the actual object itself. So, when you do this:
var a = {foo:"bar"};
a does not actually store the object itself, it only stores the memory location for where the object can be found (i.e. 0x3C41A).
But, as far as setting another variable equal to the first goes, it still works as it did with primitives - - a copy of what's in the first variable is made and given to the second variable.
Here's an example:
// An object is instantiated in memory and a is given the address of it (for example 0x3C41A)
var a = {};
// The contents of a (the memory location of an object) is COPIED into b.
// Now, both a and b hold the same memory location of the object (0x3C41A)
var b = a;
// Regardless of whether a or b is used, the same underlying object
// will be affected:
a.foo = "test";
console.log(b.foo); // "test"
// If one of the variables takes on a new value, it won't change
// what the other variable holds:
a = "something else";
console.log("a is: ", a); // The new string primitive stored in memory
console.log("b is: ", b); // The object stored in memory location (0x3C41A)
So, in your first tests, you've simply got two ways of accessing one object and then you change what a is holding (the memory location of the object) to a different object and therefore now you only have one way left to access the original object, through b.
If we try to "clear" a through by setting a = {}, object b will remain
unchanged. I don't understand why manipulating an object in this way
produces a different result than in the 1st example.
Because now we know that a = {} isn't clearing the object. It's just pointing a at something else.
In your first case:
var a = {
fname: "Jon",
lname: "Smith",
age: 50
}
var b = a;
a = {}
b remains unchanged because this is the sequence of events happening in the background:
You create an object at memory address 0x1234 with the data
fname: "Jon",
lname: "Smith",
age: 50
A pointer to that memory block is stored ina.
Then that pointer is copied to b
At this point there are two references to the same bit of memory. Altering anything in that memory block will affect both the references to it.
a = {} doesn't clear out memory block 0x1234, but creates a new object on another memory location (0x1235) and stores a pointer to that block in a. The memory at 0x1234 remains unchanged because b is still pointing to it.
There is a difference in this sort of memory management between simple variables and objects/pointers. Strings and numbers are of the simple variety and are 'passed by value' as opposed to being 'passed by reference' for objects.
Let me try to explain:
1) In your example a and b are references to one and the same object, while a.fname (or b.fname) is an attribute of that object. So when manipulating the attribute it will be changed in the object, while the references won't be affected, they still point to the same object, the object itself has been changed. a = {} on the other hand will just replace the reference to the object without affecting the object itself or b's reference to It. It's no clearance btw you only just created a new reference to a new empty object.
2) These are not objects, so there is no reference you are directly manipulating the values. That' s because there's a difference between objects and primitives which might get confusing especially in the beginning if you're not used to working with strict types.

Does JS have name binding operations? [duplicate]

So I was playing around the other day just to see exactly how mass assignment works in JavaScript.
First I tried this example in the console:
a = b = {};
a.foo = 'bar';
console.log(b.foo);
The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.
a = b = 'foo';
a = 'bar';
console.log(b);
That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.
Why does this happen?
N.B. This example could be simplified even more with the following code:
a = {};
b = a;
a.foo = 'bar';
console.log(b.foo);
a = 'foo';
b = a;
a = 'bar';
console.log(b);
(I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
In the first example, you are setting a property of an existing object. In the second example, you are assigning a brand new object.
a = b = {};
a and b are now pointers to the same object. So when you do:
a.foo = 'bar';
It sets b.foo as well since a and b point to the same object.
However!
If you do this instead:
a = 'bar';
you are saying that a points to a different object now. This has no effect on what a pointed to before.
In JavaScript, assigning a variable and assigning a property are 2 different operations. It's best to think of variables as pointers to objects, and when you assign directly to a variable, you are not modifying any objects, merely repointing your variable to a different object.
But assigning a property, like a.foo, will modify the object that a points to. This, of course, also modifies all other references that point to this object simply because they all point to the same object.
Your question has already been satisfyingly answered by Squeegy - it has nothing to do with objects vs. primitives, but with reassignment of variables vs. setting properties in the same referenced object.
There seems to be a lot of confusion about JavaScript types in the answers and comments, so here's a small introduction to JavaScript's type system:
In JavaScript, there are two fundamentally different kinds of values: primitives and objects (and there is no thing like a 'hash').
Strings, numbers and booleans as well as null and undefined are primitives, objects are everything which can have properties. Even arrays and functions are regular objects and therefore can hold arbitrary properties. They just differ in the internal [[Class]] property (functions additionally have a property called [[Call]] and [[Construct]], but hey, that's details).
The reason that primitive values may behave like objects is because of autoboxing, but the primitives themselves can't hold any properties.
Here is an example:
var a = 'quux';
a.foo = 'bar';
document.writeln(a.foo);
This will output undefined: a holds a primitive value, which gets promoted to an object when assigning the property foo. But this new object is immediately discarded, so the value of foo is lost.
Think of it like this:
var a = 'quux';
new String(a).foo = 'bar'; // we never save this new object anywhere!
document.writeln(new String(a).foo); // a completly new object gets created
You're more or less correct except that what you're referring to as a "hash" is actually just shorthand syntax for an Object.
In the first example, a and b both refer to the same object. In the second example, you change a to refer to something else.
here is my version of the answer:
obj = {a:"hello",b:"goodbye"}
x = obj
x.a = "bonjour"
// now obj.a is equal to "bonjour"
// because x has the same reference in memory as obj
// but if I write:
x = {}
x.a = obj.a
x.b = obj.b
x.a = "bonjour"
// now x = {a:"bonjour", b:"goodbye"} and obj = {a:"hello", b:"goodbye"}
// because x points to another place in the memory
You are setting a to point to a new string object, while b keeps pointing to the old string object.
In the first case you change some property of the object contained in the variable, in the second case you assign a new value to the variable. That are fundamentally different things. The variables a and b are not somehow magically linked by the first assignment, they just contain the same object. That's also the case in the second example, until you assign a new value to the b variable.
The difference is between simple types and objects.
Anything that's an object (like an array or a function) is passed by reference.
Anything that's a simple type (like a string or a number) is copied.
I always have a copyArray function handy so I can be sure I'm not creating a bunch of aliases to the same array.

What is the difference between Javascript Object, Property and Variable, are they all the same?

What is the difference between a JS:
Object, Property and Variable ?
Sorry I'm new to JavaScript but from the way I'm understanding it is a Variable is a container to store information/data types yes ?
An object is a variable but with several different properties (whereas with a variable you have one property)? name:value pairs
a property is the building blocks of objects? is that what makes an Object an Object? because it is a variable with several name:value pairs? ........
I'm supper confused!!! are all three the same are they like interchangeable?
the only example I can think of is
Human body:
Cells
Tissues
Organs
-organs are made up of tissues
-tissues are made up of cells
-cells are tissues, basically lots of cells make up tissues and lots of tissues make up organs.
So basically organs are also cells but they are made up of a lot of cells?
I'm a bit dumb and slow when it comes to learning can somebody please enlighten me?
Explain the differences between them in very simple basic language like your explaining it to a 10 year old or something please
answers much appreciated,
Thanks :)
ps There may be a part 2 to this question
the way I'm understanding it is a Variable is a container to store information/data types yes ?
Almost. A variable is a container that stores a value. Each value is of a specific data type. Common types are number, string and Boolean.
Example:
var userID = 42;
userID is a variable. It contains the value 42. 42 is a number value, i.e. it is of type number.
A JavaScript object is a value of type object. Objects are not just simple, scalar values, they are "container" values. They can themselves contain multiple different values.
Essentially objects are key-value stores, i.e. they contain one or more keys associated with a value. These key-value pairs are called properties.
Example:
var record = {
name: 'Paul',
age: 42
};
record is a variable. It contains an object as value. The object has two properties, name and age. name holds a string value, age a number value.
When one refers to 'variable' one typically imagine a container with some memory to hold a value.
Objects are variables too but dynamically transform to containers of primitives or more-complex values upon Assignment! Complex values can be objects that hold primitive data types or even other objects such in the example below :
var SNOCounter; //gives undefined ^
SNOCounter = 3;
AccObjVar = {firstName:"John", lastName:"Smith"}; //creates an JS "object" variable with two "properties" that hold 'string' type values
AccountWrapperObj = {SNO:SNOCounter,AccountName:AccObjVar};
The dynamism of object properties is such that although AccountWrapperObj which is a JS Object holds a primitive value and Object as its original value. Replacing the AccountName property with an integer can be done by just assigning it the integer value (the properties have dynamic data types just like variables in Javascript)
AccountWrapperObj.AccountName= 'Albert Einstein'; // changes the type of AccountName from AccObjVar object type to a String
----------Extra Info ---------------
^ I am not quite clear on the memory assignment part at this stage. Link says there needs to be a bare minimum memory here for referencing the variable and actually assigning it a value.
Does declaring a variable in JavaScript with var without assignment consume memory?
A variable is a binding to a value in memory and not an object.
The item in a box analogy isn’t quite right. I think that it’s more along the lines of two tin cans connected by a string, one can being the reference(variable) and the other being the value.
I'm also new to JS, so I'll tell what's helping me here
one thing that's helping me is to think about variables as 'labels', something temporary related to execution (a metaphor from Luciano Ramalho's Fluent Python book...), and not as 'boxes', a metaphor that I've seen in a lot of tutorials
so variables are temporary, and related to execution of some function, or of the whole script (depending of where they're declared... see the difference of var, let and const for more about this)
properties, on the other hand, are related to objects, attached to the obj while it or the property exists; so you cannot create a property that's not related to an obj
let myObj = {}; // 'myObj' is the 'label' of the obj we're creating
myObj.prop = true; // we create 'prop', a property of 'myObj', using the dot notation
almost everything in JS is an obj, and objs are custom types/structures for data; functions are also objects, but they're a 'special' kind of obj, we can create and return objects with them (we can execute functions to create/return objs); so
let foo; // declaring an empty variable; the word let is related to the scope of the variable, you can use var, let or const when declaring variables
foo = function(){ return {}; }; // foo returns an empty obj
myObj = foo(); // we execute foo() so that myObj is again an empty obj
the value of a property can also be an object, so we can also do
myObj.foo = function(...args){ // receives no or more arguments
const createProps = (el, i) => { // declares a variable and defines an arrow function
this[`prop${i+1}`] = el; // uses the index of the argument to create the name of the property, with the argument value
}
args.forEach(createProps); // for each arg, create a property
}
myObj.foo('some', 'new', 'properties'); // execute the function, creating new properties in 'myObj'
above, the function that creates properties for my myObj is part of myObj, as a property...
so objects and properties have to do with data structuring, how I relate the different kinds of data in my code; and functions and variables - these 'temporary labels' - have to do with execution, doin' stuff, creating objs, and so on... both 'portions' workin' together, of course

How does variable assignment work in JavaScript?

So I was playing around the other day just to see exactly how mass assignment works in JavaScript.
First I tried this example in the console:
a = b = {};
a.foo = 'bar';
console.log(b.foo);
The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.
a = b = 'foo';
a = 'bar';
console.log(b);
That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.
Why does this happen?
N.B. This example could be simplified even more with the following code:
a = {};
b = a;
a.foo = 'bar';
console.log(b.foo);
a = 'foo';
b = a;
a = 'bar';
console.log(b);
(I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
In the first example, you are setting a property of an existing object. In the second example, you are assigning a brand new object.
a = b = {};
a and b are now pointers to the same object. So when you do:
a.foo = 'bar';
It sets b.foo as well since a and b point to the same object.
However!
If you do this instead:
a = 'bar';
you are saying that a points to a different object now. This has no effect on what a pointed to before.
In JavaScript, assigning a variable and assigning a property are 2 different operations. It's best to think of variables as pointers to objects, and when you assign directly to a variable, you are not modifying any objects, merely repointing your variable to a different object.
But assigning a property, like a.foo, will modify the object that a points to. This, of course, also modifies all other references that point to this object simply because they all point to the same object.
Your question has already been satisfyingly answered by Squeegy - it has nothing to do with objects vs. primitives, but with reassignment of variables vs. setting properties in the same referenced object.
There seems to be a lot of confusion about JavaScript types in the answers and comments, so here's a small introduction to JavaScript's type system:
In JavaScript, there are two fundamentally different kinds of values: primitives and objects (and there is no thing like a 'hash').
Strings, numbers and booleans as well as null and undefined are primitives, objects are everything which can have properties. Even arrays and functions are regular objects and therefore can hold arbitrary properties. They just differ in the internal [[Class]] property (functions additionally have a property called [[Call]] and [[Construct]], but hey, that's details).
The reason that primitive values may behave like objects is because of autoboxing, but the primitives themselves can't hold any properties.
Here is an example:
var a = 'quux';
a.foo = 'bar';
document.writeln(a.foo);
This will output undefined: a holds a primitive value, which gets promoted to an object when assigning the property foo. But this new object is immediately discarded, so the value of foo is lost.
Think of it like this:
var a = 'quux';
new String(a).foo = 'bar'; // we never save this new object anywhere!
document.writeln(new String(a).foo); // a completly new object gets created
You're more or less correct except that what you're referring to as a "hash" is actually just shorthand syntax for an Object.
In the first example, a and b both refer to the same object. In the second example, you change a to refer to something else.
here is my version of the answer:
obj = {a:"hello",b:"goodbye"}
x = obj
x.a = "bonjour"
// now obj.a is equal to "bonjour"
// because x has the same reference in memory as obj
// but if I write:
x = {}
x.a = obj.a
x.b = obj.b
x.a = "bonjour"
// now x = {a:"bonjour", b:"goodbye"} and obj = {a:"hello", b:"goodbye"}
// because x points to another place in the memory
You are setting a to point to a new string object, while b keeps pointing to the old string object.
In the first case you change some property of the object contained in the variable, in the second case you assign a new value to the variable. That are fundamentally different things. The variables a and b are not somehow magically linked by the first assignment, they just contain the same object. That's also the case in the second example, until you assign a new value to the b variable.
The difference is between simple types and objects.
Anything that's an object (like an array or a function) is passed by reference.
Anything that's a simple type (like a string or a number) is copied.
I always have a copyArray function handy so I can be sure I'm not creating a bunch of aliases to the same array.

Categories

Resources