Js type conversions often occur in judgment statements, four mixed operations, and or

Conversions typically occur in these three directions: to booleans, to numbers, and to strings

Seven base types and one reference type

Basic types: Undefined, Null, Number, String, Boolean, Symbol, BigInt

Reference type: Object(function, array, Map, Set, Date, plain Object)

Boolean value

The rule is very simple, only false, 0, undefined, null, empty string “” can be changed to false, the rest of the case is true.

Judgment statements are: if judgment, while judgment, trinary operator judgment,! Judgment. Boolean strongcasts are also converted according to the rules above.

const obj = {
    valueOf: () => false,
    toString: () => false,
    [Symbol.toPrimitive]: () => false
}
if (obj) {console.log(true)}
Copy the code

valueOf

  • Null, undefined, and Date all return themselves
  • The Date type returns a timestamp of type Number
  • Function returns the defined code
  • Both null and undefined throw exceptions, but can be converted to 0 on conversion
  • Symbol can be executed, but an exception is thrown when the number is forcefully converted

toString

  • Object type is returned by default[object, Object]The second Object is the class name of the typeObject.prototype.toString.call([]) === '[object Array]', and you can redeclare itSymbol.toStringTagThe property change({[Symbol.toStringTag]: 'A'}).toString() === '[object A]'(Map,Set prototype has this property)
  • The Date type returns the local time string
  • Function returns the defined code string
  • Both null and undefined throw exceptions, but can be converted to'null','undefined'
  • The array type calls the toString method for each item and then callsjoin(',')Turn the string
  • Symbol can be executed, but an exception is thrown when the number is forcefully converted
  • All others return the corresponding string, which is not described here

toPrimitive(value: any, type? : string | number)

ToPrimitive before we get to numbers and strings

This method defines the transformation rules

  1. If it is a base type, return it directly
  2. If the object declares a Symbol. ToPrimitive property, the conversion only executes the Symbol. ToPrimitive method, which takes a type argument and returns the underlying type, or throws an exception
  3. If toPrimitive type conversion is specified, toString is executed if type is string, and valueOf is executed if type is number. If one of the methods does not return the base type, another method is called. If the base type is not returned, an exception is thrown. (The following rules apply if one is executed before the other, and no underlying type throws an exception)
const obj = {
    valueOf: () => '123',
    toString: () => 'Hello',
}
console.log(String(obj)) // Hello
console.log(Number(obj)) // 123
Copy the code

The following are cases where the Symbol. ToPrimitive attribute is not declared

  1. If the type is Date, the toString method is executed first. By default, the local time string is returned. If overwriting results in no return of the underlying type, valueOf is executed
  2. For other types, check whether they are basic types. If they are, return them directly. If they are not, run valueOf and then toString

The transfer of numbers

  1. ToPrimitive rules pass in type as Number, return the base type, and then
  • Null, undefined is converted to 0
  • False converts to 0 and true converts to 1
  • If the string is in pure numeric format'1','+ 1','1.1', can be turned,' 'An empty string can be converted to 0, otherwiseNaN
  • The Symbol type throws an exception that cannot be converted
  1. The four mixed operations are the same as Number except for the plus sign
  2. A plus sign+: If either side is converted to a string by default via toPrimitive, both sides of the plus sign are converted to a string. If there are no strings, they are converted to numbers. The plus sign is used by itself+ '1'Is called to convert Number to a Number
  3. In a greater than or less sign, both sides are converted by Number. If either side fails to convert, false is returned

In parseInt, parseFloat, the first non-number (non-+ -.) is encountered. Format to terminate

String conversion case

  1. String forcibly converts a String using toPrimitive rules, passing in type as String, returning the base type, and then converting according to toString rules
  2. If one side of the plus sign is converted to a String by the toPrimitive rule, the other side needs to be converted to a String by String

The double equal case ==

The triple equal case is the base type comparison value, and the reference type comparison store the memory address.

The double equal sign causes a type conversion

  1. Null and undefined do not convert and are equal to each other but not to anything else
  2. If the type on both sides of the equal sign is the same, the base type compares the value and the reference type compares the memory address stored
  3. Boolean can only be converted to numbers first, false to 0 and true to 1
  4. If toPrimitive on one side is a number, the other side should also be converted to a number for comparison; otherwise, the value is false
  5. If the toPrimitive on both sides is not a number, it needs to be converted to a string for comparison
  6. NaN and NaN are never equal

example

Note that {} at the beginning of an expression will be parsed into blocks by A JS engine (such as V8)

Const fn () = = > {} / / final no return value const fn = () = > ({}) / / the last returns an empty object {} {} + + 1 / / 1 [] / / 0 {a: 1} + 1 / / throw an exception, because in block a: 1 + {// '1[object, object]'Copy the code

{} + []: toPrimitive process (omits a little bit) : {} parsed into blocks, omitted, equivalent to + [], [] converted to a number will call valueOf to get [] not an underlying type, then call toString to return an empty string “”, and then convert to a number to get 0

However, in some special cases {} will not be parsed into blocks, such as {} + {}, {} + function a() {}, etc., in older browsers may be parsed into blocks, modern browsers are gradually fixed and unified. The author also did not understand, the big guy that knows troublesome message instructs.

So, when we’re programming, if we want to get an object, let’s put a little bracket around it to avoid any possible problems

Example 1 Console. log({} + []) {} was not parsed into blocks because it was passed as an argument

[] + 1: toPrimitive [] + 1: toPrimitive

[] ==! [] The Boolean value to the right and the empty string to the left is converted to the number 0, which is equal to the empty string

Example 4: ‘0’ == 0 == ” before true, true and empty string are converted to digits 1! == 0, so the result is false