Interview Failure

One day, to an interview, encountered such a question:

[] + [] {}, {}1+ []Copy the code

????? WTF, who writes code like that? Okay, I’m wrong. Don’t hit me. What do you do after that? Of course I’m going to learn a wave, so I’m going to go around the world and I’m going to share a wave if there’s something good, so let’s go into the world of JavaScript implicit conversion.

Add operation

The rules for adding in JavaScript are very simple. It just adds numbers and strings. Anything that is not of either type is converted to the original data type.

In JavaScript, there are two types of data:

  • Primitives: undefined, NULL, Boolean, number,string,symbol
  • Everything else is an object, including arrays, functions.

So how does an object get converted to a primitive data type? Don’t panic. Let’s keep watching.

ToPrimitive

JS has an internal operation ToPrimitive(), which is used to convert an object to its original data type.

ToPrimitive(input, PreferredType?)
Copy the code

This function takes two arguments:

  • Input: This parameter is the value of the input.
  • PreferredType: This parameter can be Number or String, which indicates which raw data type our object will be converted to first. If this parameter is missing, it defaults to String for Date instances and Number for all others. The transformation steps are also different because of this parameter.

Now let’s look at how it transforms for different parameters.

PreferredType for Number

  1. If input is a primitive type, return input directly.
  2. Otherwise, if the input is an object, the object will be calledvalueOf()Method that returns if the result is a primitive type.
  3. If the last step still returns the object, then go back to calling the object’stoString()Method that returns if the result is a raw data type.
  4. Uncaught TypeError: Cannot convert object to Primitive value

PreferredType String

Without going into details, when the argument is String, the second and third steps above are swapped, that is, toString() is called before valueOf() is called.

+ operation

value1 + value2
Copy the code

The above operation is as follows:

  1. Convert two operands to primitive data types:
 // PreferredType is omitted, so the non-date is Number and the date is String.
prim1 = ToPrimitive(value1)
prim2 = ToPrimitive(value2)
Copy the code
  1. If prim1 or prim2 is a string, convert it to a string and return the result of the concatenation.
  2. Otherwise, both priM1 and prim2 are converted to numbers and the sum of the results is returned.

The valueOf and toString

These are both properties of Object, and you can define them yourself. For now, let’s look at what these two methods return in the following cases.

/ / object
const a1 = {
  a: 1
};
console.log(a1.valueOf());
console.log(a1.toString());
/ / array
const a2 = [1.2.3];
console.log(a2.valueOf());
console.log(a2.toString());
/ / method
const a3 = function() {
  const a = 1;
  return 1;
};
console.log(a3.valueOf());
console.log(a3.toString());
Copy the code

Print the above code on the console to see:

  • Object: valueOf() returns the object itself, and toString() returns [object object].
  • Array: valueOf() returns the object itself. Array overrides toString()join(',')The return value of, for example[1, 2, 3]. The toString ()Return “1, 2, 3”.
  • Methods: valueOf() returns the method itself. Function also overwrites the object’s toString(), which converts the code to a string value and returns it.

Take a chestnut

Okay, based on what we said above, those interview questions were a lot of water. Let’s take a look.

[] + {}Copy the code

How do we analyze it? Here, we first convert [] and {} to the raw data type, ToPrimitive([]) and ToPrimitive({}), PreferredType defaults to Number, obviously [].valueof () is still an object. So we continue, [].toString() results in “”, and the same parsing process {} converts to “[object object]”.

Ok, so now this is “” + “[object object]”, and we know that + concatenates operands as long as there’s a string, so the result is “[object object]”.

However, when I tested it, I found a few special cases, {}+1 and {}+[], which printed 1 and “” on the console. Strange, right? I did some research and found that different browsers parse it differently. It treats the first {} as a block of code, so the top formula becomes +1 and +[], hence the above result.

conclusion

Well, after exploring this, I’m sure you won’t be stuck with these questions, but keep in mind that {} in the previous case may have different results depending on the browser. Of course, if you wrap {} in () this way, you won’t have a problem, or declare it in use first.

More resources

  • What is {} + {} in JavaScript? The author has the title of Ruan Yifeng from Germany

More articles are in my blog storehouse, if you find them useful, welcome star, thank you very much.