Setting a variable equal to another variable [duplicate] - javascript

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.

Related

Assigning one array to another javascript

So array in javascript are assigned by references so for example
let a = [1,2,3];
let b = a;
a = [];
console.log(b);
Shouldn't it print empty array as a is assigned to empty array and b and a are point to same.
I know that such behavior might seem weird. However, as other writers already mentioned, what happens is that by writing ‘a = []’ you actually assigned ‘a’ a new reference (i.e. you are not manipulating the ‘old’ array any more), and ‘b’ will hold an old reference to a memory location where ‘old’ array was initially assigned and break a relationship with ‘a’. Hence, there will now exist 2 references instead of an initial 1.

What is reference and How to know reference of the object in javascript

What is the reference in object and how to see the reference allocated to the object in javascript.I used lodash _.clone() in an object and i made a example bellow
var Obj = {id : 0, box: 0, ei : 0};
var model = {id : 0,ob : [{c: 1, a: 0}],com: _.clone(Obj)};
var old=_.clone(model)
old.id=1;
console.log(old.id===model.id); //false correct
old.com.id=1;
console.log(old.com.id===model.com.id);//true
while updating the old.id as 1 the model id has not updated,But while updating the old.com.id as 1 now the model.com.id has also updated why?
_.clone does a shallow copy. This means that it creates a new object, then for every value in the old object, it assigns the same value to the new object. For primitives (booleans, numbers, strings), this means it's copied. This is necessary so many different references can all have a value of "1" but when one of them is updated they don't all get updated. If it's a reference (Objects and Arrays), the assigned value and the original now refer to the same thing. These rules are true any time you assign something.
For example:
var a = {value:1}
var b = {value:2}
a.b = b // this sets the property "b" in a to the reference of the 'b' object.
// so a.b and b now reference the same object
// so "a.b.value" is the *same* location in memory as "b.value"
// so if you update a.b.value or b.value you'll see it change in both references (because they are the same)
This "same spot in memory" is the key. Continuing the example:
var c = _.clone(a)
// these three lines are equivalent to the line above
var c = {}
c.value = a.value
c.b = a.b
// "c.b.value" is the "same spot in memory" as "a.b.value" and "b.value"
// So when you set it to a new value that value will change for all objects
// but "a.value" was just copied to c when it was created
// So "c.value" and "a.value" are different spots in memory
// So changing "c.value" has no effect on "a.value"
Sorry if the comments are a bit hard to read but I think it helps to see it one line at a time versus a stream of sentences.

Why number are immutable in Javascript?

I have read the question and answer here:
javascript numbers- immutable
But it's not enough clear for me why the number (primitive type) are immutable? Just because they create a new reference but not overwrite the value?
If on each assignemt is created a new reference
var x = 5;
x = 1;
Would we have 100 times a new reference in the following loop?
while (x < 101)
{
x++;
}
Is that efficient? I think I am not seeing correctly.
I'm honestly not quite sure what kind of answer you expect since I don't quite understand what you are confused about. But here we go:
Would we have 100 times a new reference in the following loop?
Variables are just containers for values. At a low level a variable is basically just a label for a memory address or a register. E.g. variable x might point to register R1.
x++ would simply increment the number that is stored in that register by 1. Lets assume our register looked like this:
R1: 5
After incrementing it, which can be a single operation, such as ADD R1 1, we would get
R1: 6
I.e. we simple overwrote the previous value with a new one. And we do that multiple times.
Is that efficient? I think I am not seeing correctly.
Incrementing a number by one is as simple of an operation as it can get.
Sure, you could implement mutable numbers on a higher level, but it certainly wouldn't make things more efficient or simpler.
Mutability doesn't make much sense for "single value" values, because mutating such a value basically means replacing it with a different value "in place".
Mutability makes more sense for values that are composed of other values such as lists and dictionaries, where one part changes and the other stays the same.
Additionally, mutability only seems relevant when a language has reference type data types. With that I mean that multiple variables can hold a reference to the very same value of a data type. Objects are reference-type in JavaScript, which allows you to do this:
var a = {foo: 42};
var b = a;
b.foo = 21;
console.log(a);
If data types are not of a reference-type, called value-type, (which primitive values are in JavaScript), then mutability doesn't matter because it would be indistinguishable from immutability. Consider the following hypothetical scenario with a mutable, value-type number:
var a = MutableNumber(42);
var b = a; // creates a copy of MutableNumber(42) because it's a value type
a.add(1);
console.log(a, b); // would log 43, 42
In this scenario it is not possible for two variables to refer to the same mutable number value, a.add(1) is indistinguishable from assigning a new value to a (i.e. a = a + 1).
I could understand your question , the thing is , inside the while loop , everytime the x will point to the new value , whereas the old value will be made ready for garbage collection , so the memory is mantained still.
Read this for better understanding :
https://developer.mozilla.org/en-US/docs/Glossary/Mutable
So about the mutablity , your understanding is correct , the variable references the new value , the old value isn't changed , hence primitive values are immutable.
Refer: https://developer.mozilla.org/en-US/docs/Glossary/Primitive
Mutation is a change of state while numbers (the primitive type) are pure state objects. Any mutation to such a "object" state is actually a new number. Number itself is like an identifier of a mutation of bits in a cell of computer memory.
Therefore numbers are not mutable. Same as colors or characters.
It is also worth claryfining that a new number will ocupy the same memory cell as the old one for any given variable. Actually replacing the old one. Therefore there is no performance hit of any kind.
i dont understand entirely this,
var a=12;
a=45;
we can infer from ;
1.firstly interpreter allocate a chunk of memory and locate 12 to this area.
actually (a) is label of this memory area.
2.than, interpreter allocate a new memory cell and locate 45 to this area.
lastly (a) is associated with this new memory cell. The memory cell that contain 12 is destroyed by garbage collector.
Primitive values vs. references:
In JavaScript values of type boolean, undefined, null, number, symbol, string are primitive. When you assign them to a variable or pass them as an argument to a function, they always get copied.
In contrast objects have two parts to them: Object (it's data) is stored in one chunk of memory and what you assign to a variable is a reference pointing to that object. Object itself is not copied on assignment.
Because numbers are always copied when you assign them to a variable it is impossible to change a number and see that change through some other variable without actually assigning a new value to that variable.
In contrast when you change a field on an object, all variables pointing to that object will see that change.
Let's see some examples:
var a = 1;
var b = a; //This creates a new copy of value 1
console.log(a, b); // 1 1
a = 2;
console.log(a, b); // 2 1
var obj_a = {attr: 1};
var obj_b = obj_a; //This makes a new reference to the same object.
console.log(obj_a, obj_b); // {'attr': 1} {'attr': 1}
obj_b.attr = 2;
console.log(obj_a, obj_b); // {'attr': 2} {'attr': 2}
Immutable objects: immutable.js
Libraries like immutable.js provide types that combine properties of primitive types and objects: Types from immutable.js behave as ordinary objects as long as you don't change them. When you change a property of an immutable object, a new object is created and the change is only visible through that new object. The benefit is that you save space in memory and you can quickly check equality of objects by just comparing their references. You get a set of types that behave like integers but you can store more complex structures in them.

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

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

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

Categories

Resources