Comparison of strict equality of objects in JS [duplicate] - javascript

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.

Related

Referencing an internal variable in a JS object [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 5 years ago.
In a simple JS object like this:
var LeadserData = {
agent_id: 2,
object_queries: {
emails: {
url: "/manual_emails/",
method: 'GET',
send_data: {
the_id: this.agent_id
}
}
}
}
it is obviously possible to access the agent_id simply like this:
LeadserData.agent_id = 100;
alert(LeadserData.agent_id);
This obviously returns 100. But why does not the internal reference of this.agent_id work?
alert((LeadserData.object_queries.emails.send_data.the_id));
I was expecting this to come out as "100" as well, but instead it is undefined. The whole fiddle is here: https://jsfiddle.net/h88zc5nw/1/
What is the explanation for this behaviour, and how can I tweak this to return the expected 100.
First of all, you are using an object literal. You can't use this inside an object literal, at least it won't be what you think it is. It will be whatever this available while the object literal is constructed.
Second, even if we assume that the above works, numbers are native types, they won't be shared via their references. So changing LeadserData.agent_id won't affect LeadserData.object_queries.emails.send_data.the_id even if you have assigned one to the other. Native types are copied on assignment, not passed around using a reference (like you would do with an object).

Hard Copy vs Shallow copy javascript [duplicate]

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.

Boolean Logic Regarding empty arrays. [duplicate]

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 6 years ago.
quick question:
why does this return false? Just curious.
var myArray = [];
var myArray1 = new Array();
console.log(myArray === myArray1)
Two distinct objects are never === to one another (nor are they ==, for that matter). Object equality means that the two objects are really just one object; that is, that both sides of the === operator are references to the exact same object.
So, this will give you true:
var a = [], b = a;
console.log(a === b);
Every time you do
new Array()
or
= []
A new instance of the Array constructor is assigned to the variable. So when you do a equality check they aint same. Just as same as when two instance of a class aint same.

JavaScript array and object in single variable? [duplicate]

This question already has answers here:
Add a property to a JavaScript array
(5 answers)
Closed 7 years ago.
I recently came across some code which I am a little confused about. Below is similar code, have a look:
var x = [];
console.log(x); // prints [] (no surprise)
x[0] = "abc";
console.log(x); // prints ["abc"] (no surprise)
x["test"] = "testing"
console.log(x); // prints ["abc"]
console.log(x.test); // prints "testing"
so in this case.. the same variable, x, is both array and an object. How is this possible? If it acts as both, then console.log(x) should print something like ["abc",test:"testing"] but that syntax is wrong.
So whats happening in this case?
All Arrays are Objects, (not only them, everything in JavaScript is an Object (except the primitives though))
console.log([] instanceof Object);
// true
just that they are special kind of objects which process integer keys differently.
So, you can expect them to act like normal JavaScript Objects. You can add arbitrary properties to them.
About the console.log result,
[ 'abc', test: 'testing' ]
is just a representation given by the implementation. If the representation has a key : value format, then it is a normal property associated with that array. That's all.

Overloading [] operator for arrays in Javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How would you overload the [] operator in javascript
Is it possible to overload the [] operator for arrays in Javascript?
For instance I would like to modify the behavior of the bracket so that when it accesses an index out of range it returns 0 instead of undedined.
I know I could probably get away with something like this:
function get(array, i) {
return array[i] || 0;
}
But that's not really modifying the behavior of arrays the way I want.
Since [] is not an operator, you can't "override" it, but you can add property to Array's prototype, which may be helpful in your specific case. Hovewer, it is a bad practice:
Array.prototype.get = function(i, fallback) { return this[i] || fallback; }
a = [1, 2, 3]
a.get(0, 42)
1
a.get(4, 42)
42
[] is not an operator, and you can't override it.
You can override accessors for other javascript objects (that is override ['somespecificvalue'] for writing or reading) but not the [] of arrays.
I'll add I'm glad you can't override it. I don't see the point except in making a whole application unreadable (an application where the basic syntactic elements can't be understood before you've read the whole code to be sure there isn't a change is unreadable).

Categories

Resources