This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 7 years ago.
I was curious, so I tried this out:
var test = example = 5;
Now, this is a somewhat common way of defining things...
(for instance in node, module.exports = exports = ...)
The above be equivalent to:
example = 5;
var test = example;
Now, if variables don't actually hold a value, but are rather references to values in the memory, when I change example, if test is referencing example which is referencing a value, shouldn't test also have that same value as example? Lets try it:
var test = example = 5;
example = 7;
console.log(test, example);
... Now, the output isn't really what I expected, due to what I put above.. You get this:
5 7
But how is test still 5 if test is referencing example, and example is now 7? Shouldn't they both be 7?
EDIT Tried using Objects instead... But I get the same behavior:
var test = example = {"hello":"world", "foo":"bar"};
example = {"test":"example"};
console.log(test, example);
This outputs:
Object {hello: "world", foo: "bar"}
Object {test: "example"}
So, they're still not the same like I expected.
var a = {}; // There is one object in memory
var b = a; // now both `b` and `a` refer to that object
a = {}; // now we create another object and put a reference to it to an `a`
// we haven't changed `b` so it refers to the former object
And to summarize: in JS you cannot change the value of another variable. Value of variables a and b in the example above is a reference, not the object itself. And the only way to change the value of the variable - is to re-assign another value to it. So you cannot change the value of a variable indirectly in JS, at all (?).
When speaking about java script, variables can accept multiply values. JavaScript is a very 'forgiving' language let's call it like this.
So, if you said for example:
var test = example = 5;
test would still be 5, because test is now given the value of 5. test is but a reference in this case to example.
the actual value of example, is 7.
example = 7;
So yes, it's a bit odd, But javascript behaves a bit differently then other programming languages.
Related
This question already has answers here:
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 3 years ago.
I have an object with an array (of class objects) as one of its values. I have a function that, in part, runs a class method on one of the objects inside that array (within the object).
When I run my code, printing the array before and after the function, the change is both present before AND after the function runs.
Why is this happening? Hoisting?
As a test, I created another key:value pair in the object such that the value is an integer, and changed my function to just bump that integer up 1. Here, it works fine - the print of my object before the function has that integer as 1, and then afterward has the integer as 2.
I also tried NOT using a class method on the object to make the adjustment, and it still failed.
class Book{
constructor (color, title, pagecount){
this.color = color;
this.title = title;
this.pagecount = pagecount;
}
changePages() {
this.pagecount += 50;
}
}
let book1 = new Book("Red", "Book1", 100);
let book2 = new Book("Blue", "Book2", 200);
let book3 = new Book("Green", "Book3", 300);
var myBookArr = [book1, book2, book3]
var myObj = {arr: myBookArr, integerTest: 0}
function thisDoesStuff(){
//other operations not related to myObj
myObj.arr[0].changePages();
}
When I run the below, in BOTH console.logs, it shows that arr[0] (which is book1) has 150 pages.
console.log(myObj);
changePages();
console.log(myObj);
I am expecting the first console.log to show book1 as its original value, then the function changes it.
Please, hover on the icon with i letter on it near your log.
You will see, that Chrome (if you using Chrome, of course) will say:
Value below was evaluated just now
It happens because objects and other complex entities are being passed by reference, not by value. So, when you are expanding you log, browser getting up-to-date value of the reference.
Try to console.log copy of your value (e.g. console.log({...myObj})), or use JSON.stringify or other string-like representation of your object.
Note, that it is not error in your code. It is just a feature of the console.log, so (if I interpreted it correctly) your code works just fine :)
Your code is correct, it's all based off when the browser decides to evaluate the object for console.log output.
See post here that another user was having a similar question:
Weird behavior with objects & console.log
I just started learning about Dart.
Before Dart, I worked with Javascript and have some experience.
Now, as I was going through the documentation from Tutorial Point. They have mentioned something like this
All variables in dart store a reference to the value rather than
containing the value. The variable called name contains a reference to
a String object with a value of “Smith”.
In Javascript, I guess arrays and objects are reference types.
Meaning, If we do something like this
[Update:] This code snippet is incorrect
let a = ["apple", "orange"]
let b = a
a = ["banana"]
console.log(b) //["banana"]
but that is probably only for objects and arrays in JS (and not for const and let)
let a = 5
let b = a
a = 7
console.log(b) //5
From the quote,
All variables in Dart store a reference to the value
[Question:] Does this mean that even things like int, string.. and every variable we create in Dart are references? and the equivalence of the above code will print 7 in Dart or I am getting something wrong (in general)?
let a = 5
let b = a
a = 7
console.log(b) //7
Everything is an Object in Dart. Some objects are mutable - that is they can be modified, and some are immutable, that is they will always be the same value.
When you assign with var b = a; both b and a will reference the same Object, but there is no further association between the names b and a. If you mutate that Object by calling methods on it or assigning to fields on it (things like List.add for example) then you will be able to observe the mutated Object through either name b or a. If you assign to a then the variable b is unaffected. This is true in javascript as well.
The reason some types, like numbers or Strings, appear special is that they cannot be mutated, so the only way to "change" a is to reassign it, which won't impact b. Other types, like collections, are mutable and so a.add("Banana") would be a mutation visible through either variable referencing that list.
For example, with assignment:
var a = ['Apple', 'Orange'];
var b = a;
a = ['Banana']; // Assignment, no impact to b
print(a); // [Banana]
print(b); // [Apple, Orange]
With mutation:
var a = ['Apple', 'Orange'];
var b = a;
a.clear(); // Mutation, the _list instance_ is changed
a.add('Banana') // Another mutation
print(a); // [Banana]
print(b); // [Banana]
This question already has answers here:
Copy array by value
(39 answers)
Closed 4 years ago.
I found a really weird (for me) problem
I have this global variable ARRAY
var A = [1,2,3,4]
then inside a function, I made local var and assign previous global var to it
function someFunc() {
var X = A;
}
I then made another local Var and assign it with the first local var's value
var Y = X;
I then push a new value to Y
Y.push(6);
but the, the new value (6) didn't only pushed to Y, but also to the 2 original array (X and A). What happened? Doesn't it supposed to only change Y?
Please help, thank you.
Here is my full code:
var A = [1,2,3,4];
function someFunc(){
var X = A;
var Y = X;
Y.push(6);
console.log(A);
console.log(X);
console.log(Y);
}
$("#test").click(function(){
someFunc();
});
as you can see, it is triggered by clicking on element with id #test.
All three console.log, even thought represent different variable, it return the same result, ARRAY with 6 on it
Edit. Yes there is a similar question to this, but even though the problem is similar and the solution is identical, but the initial understanding is what different. In my question, I initially asked "Why", because I am not aware of those variable actually 'refer' to same array instead of 'assigning', so I have no idea if I should search for how to assign instead of refer, since I assumed that using = means assigning, sorry
What happens is that you do not copy the array you just reference it. You can use the method slice to create a copy of it:
var X = A.slice();
Do mind that you can use this approach only with primitive values. Check this if you need to deal with objects How do you clone an Array of Objects in Javascript?
Your arrays aren't cloned: assigning a variable does not clone the underlying object.
You can shallow-clone an array using the slice method:
var cloned = original.slice();
But array and object items within the array are not cloned using this method. Numbers and strings are cloned, however, so this should work fine for your case.
An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.
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.
This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 9 years ago.
Not sure if this is the correct way to word my question. If I set up the following piece of JavaScript code:
var x = 5;
var y = function(z) {
z=7;
return z;
}
y(x);
x;
I get 7 returned from the function call but x stays its original value. I thought JavaScript variables call by reference so how come x's value isn't actually changed through the function?
The real problem here is that you're not mutating anything; you're just reassigning the variable z in the function. It wouldn't make a difference if you passed an object or array.
var x = ['test'];
var y = function(z) {
z=['foo'];
return z;
}
y(x);
x; // Still ['test']
Now, what others have said is also true. Primitives cannot be mutated. This is actually more interesting than it sounds, because the following code works:
> var x = 1;
> x.foo = 'bar';
"bar"
> x
1
> x.foo
undefined
Notice how the assignment to x.foo was seemingly successful, yet x.foo is nowhere to be found. That's because JavaScript readily coerces primitive types and object types (there are "object" versions of primitives, that are normal objects). In this case, the primitive 1 is being coerced into a new object (new Number(1)), whose foo attribute is getting set, and then it is promptly destroyed, so no lasting effects occur.
Thanks to #TeddHopp about this note:
Only the value is passed for all variables, not just primitives. You
cannot change a variable in the calling code by passing it to a
function. (Granted, you can change the object or array that may be
passed; however, the variable itself remains unchanged in the calling
code.)
If you want the value of x to change anyways you can do:
x = y(x);