0

Array: I have 2 variables with value;

var a = [1,2];
var b = [1,2];
a === b; //return false

Object:

var a = {
   value: 'foo'
}
var b = {
   value: 'foo'
}
a === b //return false

String:

var a = '1000';
var b = '200';
a > b; //return false

Why they return that ?

Dang Hoang
  • 83
  • 1
  • 1
  • 5
  • Because the objects *look* the same, that doesn't mean they *are* the same. Identical twins can look alike but they are still two distinct people. – VLAZ Nov 08 '18 at 16:06
  • Note the last comparison returns false because you are comparing strings, ie comparisons are done lexicographically and not numerically – Patrick Evans Nov 08 '18 at 16:08
  • `===` has greater constraints than `==` . So that being said, for the Arrays, it isnt pointing to the SAME object, but different objects with the same attributes. For the Objects, the same reason. For the STRINGS on the otherhand, it is doing a string compare, and since the character 1 is less than the character 2, A is actually less than B. – Fallenreaper Nov 08 '18 at 16:09

1 Answers1

0

var a = [1,2];
var b = [1,2];


// Here you compare the instances of the Array which are objects.
// The values are not compared

console.log(a === b);

// To compare the values do :
console.log(a.length === b.length && a.every(x => b.includes(x)));

console.log('-----------');

var a = {
   value: 'foo'
}

var b = {
   value: 'foo'
}

// Here it's the same thing, you compare the object 
// (the container) and not the content
console.log(a === b);

// To compare the values do :
console.log(a.value === b.value);

console.log('-----------');

var a = '1000';
var b = '200';

// Here you compare two strings. What is happening is that all 
// character have a special value
// Look at google about ASCII
// 
// It compares character by character starting by the left
// 1 is inferior to 2 so 1000 is not superior to 200
console.log(a > b);

// To compare the values do :
console.log(Number(a) > Number(b));
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69