Pronto
Pronto

Reputation: 179

angular extend and copy understanding

I know in javascript "=== equal value and equal type" is controlling value and type. I have two examples in angular that I am confusing.

 var o1 = { name: 'David', age: 26, skill: {} };
 var o2 = angular.copy(o1);

 console.log(o2);
 // Output: { name: 'David', age: 26, skill: {} }

 console.log(o1 === o2);
 // Output: false

 console.log(o1.skill === o2.skill);
 // Output: false
 // o2.skill is a copy of o1.skill. They don't point to the same skill object.

I have another example:

 <html>
 <body>

 <p id="demo"></p> // output of z is "true"

 <script>
 var x = 5;
 var y = 5;
 var z = (x === y);
 document.getElementById("demo").innerHTML = z; 
 </script>

In first example why === is returning false? "===" is looking only data type and value.

x and y are pointing different area also. But === returning true.

Thanks in advance

Upvotes: 0

Views: 45

Answers (3)

crashmstr
crashmstr

Reputation: 28573

If you need to compare two objects you are looking for angular.equals, as === will only tell you if they reference the same object.

Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and objects.

This will compare the objects for equivalence.

console.log(angular.equals(o1, o2.skill));

lodash also has _.eq that does the same thing if you are using that library.

Upvotes: 1

Abdullah Al Faysal
Abdullah Al Faysal

Reputation: 31

For,

example 1: angular.copy did a deep cloning and created a completely new object from sample object. So when you are using '===' matching two objects it's returning false since two objects have different references and different memory allocations. That means a change in you object 'o1' will not affect your object 'o2'. Different reference leads to a mismatch hence it's returning false.

example 2: you are matching two numbers which are value type, not reference type like objects. So javascript matching two variables with value and type. Both 'x' and 'y' have same value and same type, hence returning true.

Upvotes: 1

kernal_lora
kernal_lora

Reputation: 1155

Angular.copy(); creates new object which was assigned to o2. So when you compare two objects, each object prototypes are not same.

So they are completely two different objects.

Second one is JS by default know the data type while assigning itself. We assigned numeric values for both variables , so those variables created with the same data type.

Upvotes: 1

Related Questions