Operator function

An operator's function is simply what it does and what it evaluates to. We'll be going over each operator individually, so there's not a lot to say here beyond a few basic assumptions you can carry with you when working with operators.

In JavaScript, every operator is its own entity and is not tied to the type of operands it is operated on. This is in contrast to some other languages where operators are mapped to overridable functions or are somehow attached to the operands themselves. In JavaScript, operators are their own syntactic entity and have non-overridable functionality. Their functionality is, however, extensible in certain situations. 

When using any of the following types of operators, the language will internally attempt coercion:

  • Arithmetic operators (namely, +, *, /, -, and so on)
  • Increment operators (namely, ++ and --)
  • Bitwise operators (namely,~, <<|, and so on)
  • Computed member access operator (that is, ...[...])
  • Non-strict comparative operators (namely, >, <, >=, <=, and ==)

And to specifically override these mechanisms of coercion, you can supply valueOf()toString(), or  [Symbol.toPrimitive]() methods to any objects you intend to use as operands:

const a = { valueOf() { return 3; } };
const b = { valueOf() { return 5; } };

a + b; // => 8
a * b; // => 15

As we covered in the previous chapter's Conversion to a primitive section, these methods will be called in a specific order depending on the exact operator or language construct used. In the case of all arithmetic operators, for example, valueOf will be attempted before toString.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.10.162