Do Javascript variable assignments work by reference? [duplicate] - javascript

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 8 years ago.
I have a question about referencing objects in javascript.
Say I have a variable that is some object (lets say json) and it is called objOne - (var objOne = someJSONObject;).
If I go ahead and declare
var objTwo = objOne;
will I have two references to the same Object? Kind of like a c pointer?

To sum it up :
assignements are done by value
you never manipulate objects, only object references
This means that
you'll have two references to the same object (you can check that by changing a property of the object)
when you're passed in a variable the value of a primitive, changing your variable doesn't change other variables
EDIT : as it's a duplicate I'll delete this answer in a minute to allow a proper closing if there's no other answer. Please vote to close.

Yes, objects are passed by reference:
function changeVal(obj){
obj.value = "bar"
}
(function checkRefs(){
var myObject = {
value: "foo"
};
alert(myObject.value);
changeVal(myObject);
alert(myObject.value);
})();

Related

Javascript var reference. Could someone explains to me what's the difference between primitive and objs/array? [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Does JavaScript pass by reference? [duplicate]
(13 answers)
Closed 8 years ago.
I'd like understand why this difference (I suppose works like Java, so it's stack and heap difference)
var a = 10;
console.log(a);//10
function ChangeVal(){ b=a; b++; }
console.log(a);//10
var a = {name:"MyName"};
console.log(a);//{name:"MyName"}
function ChangeVal(){ b=a; b.name = "YourName"; }
console.log(a);//{name:"YourName"}
Assigning the value of one variable to another always involves copying the value. Thus:
b = a;
assigns the value of variable "a" to the (global! you forgot var!) variable "b". That happens in both your examples.
In the first example, the value of "a" is the number 10. In the second, it's a reference to an object. After
b = a;
in both cases, the variable "b" has the same value — a copy of the same value — as "a".
Because one reference to a particular object is as good as another, in your second example it's perfectly natural that changing the value of the "name" property on that object can be done via the reference in either "a" or "b".

Get the name property of a variable [duplicate]

This question already has answers here:
Get variable name. javascript "reflection"
(4 answers)
JavaScript: Get Argument Value and NAME of Passed Variable [duplicate]
(7 answers)
Closed 8 years ago.
I was wondering if it's possible to get the name of a variables in javascript or JQuery.
Suppose that I declare a variable in javascript like:
var customerNr = "456910";
If a function receive a variable, how can i return the name of the variable?
For example:
function getNameOfVariable(someVariable){
//return name of someVariable;
}
If I call this function like this:
getNameOfVariable(customerNr);
The function has to return a string whose value is "customerNr".
How can I do this in jquery or javascript? Some kind of reflection?
That is simply not possible!
The passed parameter doesn't even have to have a name. It could be a return value of a function or a raw literal (like "string" or 3).
No, this is not possible. Only values are transferred for primitive data types, not references, so how would you know what the "name" of the variable is? For example:
var customerNr="456910";
var customerNrAfterProcessing=customerNr;
getNameOfVariable(customerNrAfterProcessing);
Would it return customerNrAfterProcessing or customerNr?
However, you can imitate this behavior with objects.
var variableName = someMethodThatDeterminesVariableNameOrJustAConstantIfYouPrefer();
var myVariables={};
var myVariables[variableName]={};
myVariables[variableName].value="456910";
myVariables[variableName].variableName=variableName;
function getNameOfVariable(someVariable){
return someVariable.variableName;
}
getNameOfVariable(myVariables[variableName]);
Obviously, this amounts to a lot more work than just using the variableName variable directly, but it could be necessary in some more complicated situations.
See working with objects in JS reference

Updating object values in JavaScript via function [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 9 years ago.
In JavaScript I am trying to update an object value through a function, through which I am passing the object property to update.
However, this won't work - and I can see why, but don't know how to combat it!
myObject = {"testItem": "testValue"};
console.log(myObject.testItem);
function updateSomeValue(objectItem, newValue){
myObject.objectItem = newValue;
}
updateSomeValue('testItem', 'newValue');
console.log(myObject.testItem);
Now, I can see the issue here is that in the function, myObject.objectItem is expecting an item in the object called objectItem - it won't translate it to testItem.
How do I do this?
By using a different notation. Using [ .. ] you can specify the property name as a string.
function updateSomeValue(objectItem, newValue){
myObject[objectItem] = newValue;
}

Dynamically assign name to object array [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 10 years ago.
I have a javascript issue.
If I have an object array objAr, the object consists of id,name.
If I was to access objAr[0].id it returns the id value of the first object. What would happen if the object is dynamic and therefore I do not know what it consists of, is there a way to dynamically call the Object attribute?
Currently I am creating another array
var theArr = new Array("id", "name");
and call:
objAr[0].theArr[0] instead of objAr[0].id.
Is there a way to do this better using Javascript?
With Javascript you can call all of the attributes in an object without knowing the keys.
See below:
for(key in objAr[0]) {
console.log(objAr[0][key]);
}
If you just wanted the first attribute you could run:
for(key in objAr[0]) {
var attFirst = objAr[0][key];
break;
}
Additionally for the JS array you could have used square brackets.
var theArr = ["id", "name"];
hope that helps
In javascript you can always use the "array notation" in place of the "dot notation"
So these 2 lines are the same
objAr[0].id
objAr[0]["id"]

Javascript's objects added to array is pass by value or reference? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript a pass-by-reference or pass-by-value language?
In this file I have an object this.objectA and this.allAs;
this.objectA contains a few attributes.
Everytime I got a new this.objectA, I add it to the array this.allAs.
I always reassign this.objectA when I get a new one.
Later I check my array this.allAs, I found that it correctly stores different this.objectA.
How come this.objectA gets overwritten, the objects inside this.allAs didn't get overwritten? (I expect all those stored objects to to pointing to the same this.objectA, but it didn't) Javascript is pass by value for objects???
You've got to get a lot more specific about what you're doing.
JavaScript passes by reference, but if you're saving local copies anywhere, and copying those values from return statements, then you're not working from reference anymore -- they're no longer pointers to the exact same object, necessarily.
Here's something to demonstrate passing references:
Bob = { name : "Bob", age : 32 };
function giveBobTo (obj, bobject) { obj.bob = bobject; }
Billy = {};
Jim = {};
giveBobTo(Billy, Bob);
giveBobTo(Jim, Bob);
Jim.bob.cars_on_lawn = 8;
Billy.bob.cars_on_lawn; // 8;
Bob.cars_on_lawn; // 8;
console.log( "Billy-Bob equals Jim-Bob equals Bob:",
Billy.bob === Jim.bob === Bob); // true

Categories

Resources