preface

Type conversion has always been a headache in JavaScript, although this piece of knowledge is not very complex, but rather trivial, this article aims to help readers master system comprehensive review of JavaSctipt type conversion. I hope you enjoy it.

Front knowledge

Basic data types

  • number
  • string
  • boolean
  • null
  • undefined
  • symbol
  • bigint

Reference data type

  • Standard common object: Object and its subbranches
    • Standard special objects: Array, RegExp, Date, Math, Error…
    • Nonstandard special objects: Number, String, Boolean…
    • Callable/executable object “function” : function

Three types of conversion

Yes, you read that correctly. There are only three types of conversion in JS: go to Number, go to String, go to Boolean.

The first picture

So all the data type conversion behind can be seen as a primary school to do lianlianhe.

Two types of conversion methods

There are two types of conversion methods: implicit and explicit.

Explicit casting is when a developer converts between types by writing appropriate code, such as: Number(value).

Implicit conversion refers to the automatic conversion of values between types when operators are used on values of different types, such as 1 == NULL.

Go to Boolean for basic data type

According to turn

The Boolean() method can be used to explicitly convert a value to a Boolean

This is relatively easy, there are only six values that can be converted to false in JS, so we only need to memorize these six values.

These are the six values

  • false,
  • undefined,
  • null,
  • 0 (including + 0, 0),
  • “”,
  • NaN
console.log(Boolean()) // false

console.log(Boolean(false)) // false

console.log(Boolean(undefined)) // false
console.log(Boolean(null)) // false
console.log(Boolean(+0)) // false
console.log(Boolean(-0)) // false
console.log(Boolean(NaN)) // false
console.log(Boolean("")) // false
Copy the code

Note that the Boolean function returns false when it passes no arguments.

Implicit turn

Implicit type conversion usually in logic or logic is triggered when the operator (| | &&!) .

// return number type 123 instead of Boolean true // 'hello' and '123' are still internally converted to Boolean to evaluate the expression let x = 'hello' && 123 // x === 123Copy the code

Boolean conversions can only have true or false results. All values are true except “0/NaN/ empty string /null/undefined” which are false

Basic data type to Number

Refer to this table

The parameter types The results of
Undefined NaN
Null + 0
Boolean If the argument is true, return 1. Argument false, return +0
Number Returns the value equal to it
String This is a bit more complicated. Let’s do an example
Symbol An error
bigInt Cannot be converted implicitly by +, can only be converted by Number, ignoring n

According to turn

The Number(),parseInt(),parseFloat() methods can be used to explicitly convert a value to a numeric type.

Just a couple of examples

console.log(Number()) // +0 console.log(Number(undefined)) // NaN console.log(Number(null)) // +0 console.log(Number(false)) // +0 console.log(Number(true)) // 1 console.log(Number("123")) // 123 Console. log(Number("-123")) // -123 console.log(Number("1.2")) // 1.2 console.log(Number("000123")) // 123 console.log(Number("-000123")) // -123 console.log(Number("0x11")) // 17 console.log(Number("")) // 0 console.log(Number(" ")) // 0 console.log(Number("123 123")) // NaN console.log(Number("foo")) // NaN console.log(Number("100a")) // NaN console.log(Number(Symbol()))//Uncaught TypeError: Cannot convert a Symbol value to a number console.log(Number(12312412321312312n)) //12312412321312312Copy the code

As you can see from the examples above, the first four conversions are relatively simple. It’s string to Number and this is a little bit complicated, so let’s focus on string to Number as well.

The rules for converting a string to Number are as follows

  1. An empty string returns 0
  2. Ignore all leading zeros unless they are preceded by a hexadecimal 0x.
  3. Convert to an integer or floating point number
  4. If a character is not a number, NaN is returned

This conversion by Number is too strict, so I usually use the more flexible parseInt and parseFloat as well.

ParseInt parses only integers. ParseFloat parses both integers and floating-point numbers. If a string is prefixed with “0x” or “0x”, parseInt interprets it as hexadecimal.

Common conversion rules for both

  • Both parseInt and parseFloat skip any number of leading Spaces
  • Parse as many numeric characters as possible
  • And ignore the rest
  • NaN is eventually returned if the first non-space character is an illegal numeric direct quantity:

See the example

Console. log(parseInt("3 ABC ")) // 3 console.log(parseFloat("3.14 ABC ")) // 3.14 console.log(parseInt("-12.34")) // -12 Console. log(parseInt("0xFF")) // 255 console.log(parseFloat(".1")) // 0.1 console.log(parseInt("0.1")) // 0Copy the code

Implicit turn

The implicit conversion of number is complicated because it can be triggered in a number of ways.

  • Compare operations (>, <, <=, >=)
  • Bitwise operations (| & ^ ~)
  • The arithmetic operation (- + * / %) does not trigger an implicit conversion to number if any of the operands in the + operation are string operands
  • Unary + operation

Change the basic data type to String

Refer to this table

The parameter types The results of
Undefined “undefined”
Null “null”
Boolean Return “true” if the argument is true. Parameter false, return “false”
Number Again, it’s a little bit more complicated, so let’s look at an example
String Returns the value equal to it
Symbol Cannot be converted implicitly by +; can only be converted by toString, returning a string
BigInt Returns a numeric string with n removed

Explicit turn

The String() method can be used to explicitly convert a value to a String.

Just a couple of examples

Log (String()) // Empty String console.log(String(undefined)) // undefined console.log(String(null)) // null console.log(String(false)) // false console.log(String(true)) // true console.log(String(0)) // 0 console.log(String(-0)) // 0 console.log(String(NaN)) // NaN console.log(String(Infinity)) // Infinity console.log(String(-Infinity)) // -Infinity console.log(String(1)) // 1Copy the code

Again, the tricky part is converting Number to String.

Implicit turn

Implicit conversions are usually triggered when there is a + operator and one of the operands is string

“+” represents a concatenation of strings that will trigger the conversion if one of the following conditions exists

  1. If you have two sides, one side is a string, it’s a string concatenation;
  2. There are two sides. One side is the object
1 + '123'  //"1123"
1 + {}     //"1[object Object]"
Copy the code

Object to number

  1. If the object has a valueOf method and returns a raw value, JavaScript converts the raw value to a number and returns the number
  2. Otherwise, if the object has a toString method and returns a raw value, JavaScript converts it and returns it.
  3. Otherwise, JavaScript throws a type error exception.

Object to string

  1. This method is called if the object has a toString method. If it returns a raw value, JavaScript converts the value to a string and returns the string result.
  2. If the object does not have a toString method, or the method does not return a raw value, JavaScript calls the valueOf method. If the method exists, JavaScript calls it. If the return value is the original value, JavaScript converts the value to a string and returns the result of the string.
  3. Otherwise, JavaScript cannot get a raw value from toString or valueOf, in which case it will throw a type error exception.

The toString, and the valueOf ToPrimitive

toString

All objects have a toString method for any value other than null and undefined. In general, this method returns the same result as the String method. The toString method returns a string that reflects the object, but that’s where the complications begin.

Object. The prototype. The toString method according to the [[class]] internal attributes of objects, returned by the “[Object” and the class and “] “string is composed of three parts. Here’s an example:

Object.prototype.toString.call({a: 1}) // "[object Object]"
({a: 1}).toString() // "[object Object]"
({a: 1}).toString === Object.prototype.toString // true
Copy the code

We can see that when we call the toString method of an Object, we actually call the toString method of Object.prototype.

However, many classes in JavaScript define more versions of toString methods, depending on their characteristics. Such as:

  1. The toString method of an array converts each array element to a string, which is combined into a result string by adding commas between the elements.
  2. The toString method of the function returns the source code string.
  3. The toString method of a date returns a readable date and time string.
  4. RegExp’s toString method returns a string representing the regular expression’s immediate quantity.

Reading text too abstract? Let’s just write the example:

console.log(({}).toString()) // [object Object] console.log([].toString()) // "" console.log([0].toString()) // 0 Console. log([1, 2,3].toString()) // 1,2,3 console.log((function(){var a = 1; }).toString()) // function (){var a = 1; } console.log((/\d+/g).toString()) // /\d+/g console.log((new Date(2010, 0, 1)).toString()) // Fri Jan 01 2010 00:00:00 GMT+0800 (CST)Copy the code

valueOf

Represents the original value of an object. The default valueOf method returns the object itself, and arrays, functions, and regees simply inherit the default method and return the object itself. The exception is the date, which returns one of its content representations: the number of milliseconds since January 1, 1970.

var date = new Date(2017, 4, 21);
console.log(date.valueOf()) // 1495296000000
Copy the code

ToPrimitive

ToPrimitive(input[, PreferredType])
Copy the code

The first parameter, input, represents the input value to be processed.

The second parameter is the PreferredType, which is optional and indicates the type you want to convert to. You can choose from two values, Number or String.

When the PreferredType is not passed, it is equivalent to a String if the input is of date type, and a Number otherwise.

If the input is Undefined, Null, Boolean, Number, or String, the value is returned.

If ToPrimitive(obj, Number) is used, the procedure is as follows:

  1. If obj is a basic type, return it directly
  2. Otherwise, the valueOf method is called, and if a raw value is returned, JavaScript returns it.
  3. Otherwise, the toString method is called, and if a raw value is returned, JavaScript returns it.
  4. Otherwise, JavaScript throws a type error exception.

If it is ToPrimitive(obj, String), the processing is as follows:

  1. If obj is a basic type, return it directly
  2. Otherwise, the toString method is called, and if a raw value is returned, JavaScript returns it.
  3. Otherwise, the valueOf method is called, and if a raw value is returned, JavaScript returns it.
  4. Otherwise, JavaScript throws a type error exception.

conclusion

Both primitive types and object types will only be converted to one of the above three types. So it’s just a matter of figuring out which genre to switch to in which scenario.

  • All data types are converted to Boolean, except 0,null,undefined,””,NaN, and false, which will be converted to false.

  • Base data type to Number, refer to this table

The parameter types The results of
Undefined NaN
Null + 0
Boolean If the argument is true, return 1. Argument false, return +0
Number Returns the value equal to it
String This is a bit more complicated. Let’s do an example
Symbol An error
bigInt Cannot be converted implicitly by +, can only be converted by Number, ignoring n
  • Refer to the data type to Number, as per this rule

    1. If the object has a valueOf method and returns a raw value, JavaScript converts the raw value to a number and returns the number
    2. Otherwise, if the object has a toString method and returns a raw value, JavaScript converts it and returns it.
    3. Otherwise, JavaScript throws a type error exception.
  • Base data type to String, refer to this table

The parameter types The results of
Undefined “undefined”
Null “null”
Boolean Return “true” if the argument is true. Parameter false, return “false”
Number Again, it’s a little bit more complicated, so let’s look at an example
String Returns the value equal to it
Symbol Cannot be converted implicitly by +; can only be converted by toString, returning a string
BigInt Returns a numeric string with n removed
  • Go to String for base datatype, follow this rule
    1. This method is called if the object has a toString method. If it returns a raw value, JavaScript converts the value to a string and returns the string result.
    2. If the object does not have a toString method, or the method does not return a raw value, JavaScript calls the valueOf method. If the method exists, JavaScript calls it. If the return value is the original value, JavaScript converts the value to a string and returns the result of the string.
    3. Otherwise, JavaScript cannot get a raw value from toString or valueOf, in which case it will throw a type error exception.