How to compare two types JavaScript? - javascript

How can I compare two the same types against each other in JavaScript?
So a == b should return true, because they are both arrays.
So it doens't matter what the contents of the variable are. The comparison should be something like this;
var a = [];
var b = [];
var c = "this is a string";
var d = "this is also a string";
if(a type == b type) // true because both arrays
if(c type == d type) // true because both strings
if(a type == d type) // false because not the same type (string) or (array)

To compare two types in javascript, use typeof.
(function () {
var a = [];
var b = [];
var c = a;
var d = "a";
var e = "a";
console.log(typeof(a) == typeof(b));
console.log(typeof(a) == typeof(c));
console.log(typeof(d) == typeof(e));
})();

a and b are not exactly the same. If the type is a reference type, comparing them just checks their references. In this case a and b are arrays, but they have separate objects in the memory and separate references to them.
When you assign a to c, it just copies the reference from a and assigns it to c. And now c also refers to the same object as a. So while comparing a and c returns true, because they have the same reference value(address of the memory).
Something like this. (number in the [] is the address of the memory, number in the () is the value)
a(0x1616) ---------> [0x1616] <--|
b(0x1717) ---------> [0x1717] |
c = a; |
c(0x1616) -----------------------|

[] is Javascript Array type Object.
== does type check first.
when you are doing a == b although they are both array but they are different array object like they have different values and references.So it becomes false
when you are assigning c = a. It's called passing reference of a array to c.
therefore they are pointing to same array object. so a == c becomes true.

If both operands are objects, then JavaScript compares internal references which are not equal when operands refer to different objects in memory.
The variables a and b refer to two objects with identical properties, but they are each distinct instances. On the other hand a and c both refer to the same instance.
The reason for this is that internally JavaScript actually has two different approaches for testing equality. Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference. That comparison by reference basically checks to see if the objects given refer to the same location in memory.
Please see below snippet for comparison of objects in Javascript.
(function () {
var a = [];
var b = [];
var c = a;
var d = "a";
var e = "a";
console.log(a == b);
console.log(a == c);
console.log(d == e);
})();

Related

How can I see if 2 specific string variables added

How can I check if 2 variables with the same value are the same variable?
For example in the below code I created 2 variables with the same values and i pass:
function check_var(v){
// Check if "v" (string) came from a or b
}
let a = "string";
let b = "string";
check_var(b);
I able to install v8 engine locally and change the the source code, but i am looking for more easy way to do it.
One way to do it is if I had a method in javascript that returns a unique value for each variable based on the variable name.
One more way to solve the problem is by logging all the javascript actions, by doing that i could see after the code executed if var a is the var that got into the check_var function.
In general you cannot, JavaScript doesn't have a universal identity equality operator.
Strings, numbers and some other simple values can only be compared by value. Tho objects, including arrays are compared by identity.
const a = [1]
const b = [1]
a===b // false
If this is important you could box the value
const a = { value: 'string' }
const b = { value: 'string' }
const c = a
a.value === b.value // true
a === b // false
a === c // true

Object comparisons in JavaScript

I would like to understand the weird behaviour of JavaScript identity and equality operator as given below.
var a = {};
var b = {};
a === b; //false
a == b; //false
var c = '';
var d = '';
c === d; //true
c == d; //true
All four variables a ,b ,c and d are objects. But when comparing them, first case yields false whereas second one true.
I studied comparison from the following source: https://msdn.microsoft.com/en-us/library/d53a7bd4(v=vs.94).aspx
According to the above article, except number and boolean everything is compared by reference instead of value. So how the first case returns false and second one true.
c and d in your example are strings, which are primitive types in JavaScript and compared by value.
For this reason, c == d returns true.
The article is talking about string objects created usng the new String('foo') constructor, which actually creates objects. In this case, the references are compared, returning false.
console.log(new String('foo') == new String('foo')) // false
console.log('foo' == 'foo') // true
A (primitive) string is a value type (like Number). As such === compares its value (equality).
Objects are reference types, and for them === compares identity.
Strings are a bit crazy, as there are both primitive strings and String objects (created with new String("foo")).
== works the same way as === except that it does type conversions to "make things equal if possible". For reference types this is the same as ===, except that it also equates primitive strings and String objects.
"abc" == new String("abc");
"abc" !== new String("abc");

Compare one array with an 2 dimensional array in javascript

a = [1,2,3];
b = [[1,2,3],[4,5,6]];
Why is that in javascript a== b[0] return false?
Thank you
In javascript objects are compared by references.
That said: a references to objects are compared, not the objects' contents.
Thus, One object {} will never be equal to another {} even though their contents are equal.
var a = {},
b = {}; // not equal
Whereas if you create a variable by assigning another reference to it like:
var a = {},
b = a; // equal
then both variables would hold the same reference and would be equal.

Access to object and set it null throw element of array

Very simple example:
var a = { id: 5 };
var b = { id: 6 };
var c = { id: 7 };
var arr = [a, b, c];
Now i have a function:
function remove(startIndex) {
// set objects to null from startIndex in array
}
If i try this:
arr[0] = null;
then i have:
arr[0] == null // true
a == null // false (i need true)
So, my question, how could i access to object throw any collection (array or object) and change it?
I don't want to write something like this:
function remove(startIndex) {
if(startIndex == 0) {
a = null;
b = null;
c = null;
}
if(startIndex == 1) {
b = null;
c = null;
}
if(startIndex == 2) {
c = null;
}
}
much easier to write like this (but it doesn't work):
function remove(startIndex) {
for(var i = startIndex; i<arr.length; i++) arr[i] = null;
}
I don't know exactly what you're aiming with this code you're writing, but here's how Javascript works:
Every time you instantiate a variable with a value, say an object like { id: 10 }. That object is stored in memory and a reference is returned back to your variable, say you name it a.
Now, if you say var b = a;, the same reference is now passed on to variable b. Now Javascript runtime knows you have two variables referencing the object { id: 10 }.
You now no longer want to keep the variable b, so you write b = null;. You think the object is deleted, but the Javascript runtime knows the object { id: 10 } has one reference -- i.e. the variable a -- referencing it. So it won't remove { id: 10 } from memory.
However, if you also write a = null;, then there are Zero references, and the Javascript runtime's Garbage Collector will eventually get to removing the object from memory.
All this was to get you to understand that without further housekeeping, you will not be able to achieve what you're hoping to do.
If you really want a, b, c to be null, you will have to write some code that explicitly sets their value to null too. Like a = arr[0]; b = arr[1]; c = arr[2]; whenever the array is changed. You can eval the statements and do some string templating to not write the variables by hand etc., and make a loop out of that, but that's not worth it if you only have three variables.
Hope this helps.
JavaScript doesn't have pointers, so to achieve what you want in the original way will not work.
Other than arr[0] = null, you can try setting a to null directly as well.

javascript returning difference between two objects

I have an object that looks like this:
var MyObject = {
prop1 = 12345,
prop2 = "string1",
ListOfOtherObject = an array of another type of object,
ListOfAnotherObject = an array of objects}
Let's say I have two objects: Object1 and Object2. Object2 was initially a deep-copy of Object1 and it was modified through the user's interactions with the UI. I'm looking to get the difference between both objects, especially when it comes to the arrays.
For instance, ListOfOtherObject in Object2 might contain a modified version of some objects as well as new objects.
I'm thinking about looping through each array and then looping through each object within but there might be some more efficient way to do it, especially with jquery. Or may be going with JSON.stringify and compares strings and retuns some sort of string difference. I was wondering if anyone had any suggestions on how to do this.
Thanks.
You need to specify what your comparison needs to do. For example, given:
var o = {name: 'fred'};
var p = {name: 'fred'};
var a = {o:o};
var b = {o:o};
then:
a == b; // false, a and b are different objects
a.o == b.o; // true since a.o and b.o reference the same object
but if comparing objects:
b.o = p;
a.o == b.o; // false since a.o and b.o reference different objects
or if comparing primitives:
a.o.name == b.o.name; // true since the value of both expressions is the string 'fred'
// even though a.o and b.o are different objects
Does Type or constructor matter? What about:
b.o = [];
b.o.name = 'fred';
a.o.name == b.o.name; // true or false? a.o is an object, b.o is an array

Categories

Resources