This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 6 years ago.
This may be an old question but I'm really curious about the nature of copying objects by reference as an assignment in javascript.
Meaning that if
var a = {};
var b = a;
a.name = "Renato";
console.log(b);
Object {name: "renato"}
I'm kind of new to javascript and this really caught my attention to have a shallow copy as a default for Object assignment. I searched that in order to create a hard copy, you have to create a mixin. I was wondering why was this chosen as the default since it's transformation seems to be very implicit. Thanks!
Objects and arrays are treated as references to the same object. If you want to clone the object, there are several ways to do this.
In later browsers, you can do:
var b = Object.assign({}, a);
If you want to go for a library, lodash provides _.clone (and _.cloneDeep):
var b = _.clone(a);
If you don't want to do either of those methods, you can just enumerate through each key and value and assign them to a new object.
Oftentimes it's valuable for them to be treated as references when passing through multiple functions, etc. This isn't the case for primitives like numbers and strings, because that would feel pretty counterintuitive in most cases.
Related
This question already has answers here:
Why is it Object.defineProperty() rather than this.defineProperty() (for objects)?
(3 answers)
Why were ES5 Object methods not added to Object.prototype?
(2 answers)
Closed 3 years ago.
I have have seen that three method of array are static methods are static. Array.isArray(), Array.from(), Array.of. I can understand why they are static methods. Because the variable passed to them can also be something other than array. Same is case with Number and String.
But I cannot understand that why almost all the methods of Object are static. Why keys, entries,values etc are not on prototype.
Is there any advantage of putting them as static method?
What problems we would have faced if we had Object.prototype.keys/entries/values...
The problem with Object methods being on the prototype is that objects in general can have arbitrary key-value pairs. For example, if there was such a thing as Object.prototype.values, it could very easily cause confusion when you had an object which you intended to have a values property, eg
const foo = { values: ['val1', 'val2'] };
If Object.prototype.values were a thing, to use it here, you would have to do something like
const fooValues = Object.prototype.values.call(foo);
Better for values to be a static method to avoid such name collisions.
If the properties of your objects could be functions as well, it could be even worse, for example:
const foo = {
info: ['a', 'b', 'c'],
values() {
return this.info;
}
};
Now, if Object.prototype.values was a thing, and you saw foo.values() in the code, what do you think it would mean? Was the programmer intending to call the values property of foo (which is what the code would result in), or was the programmer intending to use Object.prototype.values? It'd be an easy source of bugs and hard-to-read code.
Same thing for the other Object static methods - they could easily result in name collisions.
This question already has answers here:
How variables are allocated memory in Javascript?
(2 answers)
Closed 4 years ago.
I am looking at the spec:
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6
http://www.ecma-international.org/ecma-262/5.1/#sec-9.12
I have seen JS code do this:
var a = function(){}
var b = function(){}
var c = a;
console.log(a === b);
console.log(a === c);
the code works as expected, it seems to use strict equality - it doesn't convert the functions to strings and then compare strings - that would be crazy - it uses memory address or something like with Java, right?
How does it actually work? Does anyone know? The spec doesn't seem to mention function comparison, or objects for that matter.
it uses memory address or something like with Java, right?
Pretty much. A variable referencing an object is essentially a reference to a memory location - objects (and functions) are only equal if they reference the same location in memory. Thus, { foo: 'bar' } !== { foo: 'bar' } because each object was created separately.
All non-objects (primitives) can be considered to compare by value, though.
This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Closed 5 years ago.
Let's say we got this:
this.myObject = {"id":1};
and we want to store the state of my object as my object original as the following:
this.myObjectORG = this.myObject;
then you go on your business and change props on your object like this
this.myObject.id = 2;
and to your surprise down the road, you realize that
console.log (this.myObjectORG.id) // also reports 2
Well, that's just how JS works & I'm not questioning that.
Is there a way to preserve the state of the myObject so I can do comparisons whether its properties changed since its original state?
At some point I'd like to be able to do something like this
if ( this.myObjectORG.id !== this.myObject.id ) {
// but this condition is never true
}
Does this help:-
An Object.assign method is part of the ECMAScript 2015 (ES6) standard and does exactly what you need.
var this.myObjectORG = Object.assign({}, this.myObject);
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
This question already has answers here:
Why is it Object.defineProperty() rather than this.defineProperty() (for objects)?
(3 answers)
Closed 8 years ago.
Both of these obviously do similar things but my question is why is one on the prototype and one on the Object?
For example, both of these called differently. Is there a logical reason why this is the case?
var o = {name: "value"}
o.hasOwnProperty("name") //true
Object.getOwnPropertyNames(o); //name
//Couldn't the above have been coded so we can run o.getOwnPropertNames();
Thanks.
The problem with adding these methods to the prototype is taht they are prone to getting overloaded.
var o = {};
o.getOwnPropertyNames = 17;
//What now?
In fact, you would often see people doing
Object.prototype.hasOwnProperty.call(o, propname);
in order to avoid the overloading issue with hasOwnProperty.
This question already has answers here:
javascript variable swapping using arrays
(3 answers)
Closed 8 years ago.
Saw in a single source next:
[param_o,param_got] = [param_got,param_o];
This code swap variables param_o & param_got.But how [param_o,param_got] = [param_got,param_o] works, if [] is new instance of Array in Javascript ?
EDIT
Try checking:
var param_o = 1;
var param_got = 2;
[param_o,param_got] = [param_got,param_o];
console.log(param_o+" "+param_got);
// 2 1
This notation is called destructuring assignment and is part of Javascript 1.7:
Destructuring assignment makes it possible to extract data from arrays
or objects using a syntax that mirrors the construction of array and
object literals.
The object and array literal expressions provide an easy way to create
ad-hoc packages of data. Once you've created these packages of data,
you can use them any way you want to. You can even return them from
functions.
One particularly useful thing you can do with destructuring assignment
is to read an entire structure in a single statement.
The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.
Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.