2

Below is a typical way to check if the focus is on an element certain (txtCmd),

if(document.activeElement === txtCmd){
                return
}

I'm worried the operator=== would compare the entire element tree (every attribute and every sub-element) that would be low performance.

Does just compare the elements' Ids is better?

document.activeElement.id === txtCmd.id

PS: There are no different elements with identical ID in the page.

Edit:

I'm from C++. I want something like pointer comparison in C++,

   if(&a == &b) {}
Zhang
  • 3,030
  • 2
  • 14
  • 31
  • 3
    `===` doesn’t perform any deep comparison. – Sebastian Simon Mar 10 '22 at 08:00
  • 1
    @mplungjan Comparing IDs is no faster and may even be slower, because that’s one more property lookup and it’s character-by-character comparison rather than immediate referency-to-reference comparison. – Sebastian Simon Mar 10 '22 at 08:13
  • 2
    "_I want something like pointer comparison in C++_" For objects (like here) this is essentially what you get. – Ivar Mar 10 '22 at 08:16

2 Answers2

4

=== doesn’t perform any deep comparisons, so it’s not low-performance.

An alternative is the .isSameNode() function:

b.isSameNode(a);

Edit:

I'm from C++. I want something like pointer comparison in C++,

if(&a == &b) {}

That essentially is what == and === do in JavaScript when 2 objects are tested for equality.

JavaScript’s quality operators compare objects by reference if the operands are both objects. a == b and a === b are true only if both a and b reference the same object.

clickbait
  • 2,818
  • 1
  • 25
  • 61
  • 1
    _The isSameNode() method of the Node interface is a legacy alias the for the === strict equality operator_ – mplungjan Mar 10 '22 at 08:23
1

If you compare objects the === operator will perform a reference comparison, so it will only return true only if both operands points to the same object.

It will not cost you more performances but it just does not the same thing than comparing property litteral values.

For a deep comparison "by value" between objects, === doesn't work. You'd have to use a recursive entry by entry comparison, or compare stringified versions of the objects.

Example

const o1 = {"a":1};
const o2 = {"a":1};
const o3 = o1;
console.log(o1 === o2); // false
console.log(o1 === o3); // true
console.log(JSON.stringify(o1) === JSON.stringify(o2)) // true
Peterrabbit
  • 2,166
  • 1
  • 3
  • 19