JavaScript itself is a weakly typed language, which means that JavaScript variables have no predetermined type. The current type of a variable is determined by its value, which might be a string one second, or an array the next. So when we do something, variables can be converted from type to type, and we’ll talk about how data types are converted.

preface

Let’s start with an interview question

let result = 100 + true + 21.2 + null + undefined + "Tencent"+ + []null + 9 + false;
// The result should be?
Copy the code

Implicit data type conversions (); implicit data type conversions ();

JS data type

First, there are two broad categories of data types in the JavaScript language: primitive value types and object types

Primitive value types are what we call “value types/primitive data types”

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

And object type means reference data type

  • Standard common objects:object
  • Standard special objects:Array,RegExp,Date,Math,Error
  • Non-standard special objects:Number,String,Boolean
  • Callable/executable object “function” :function

Conversion between types

Type conversions can be divided into two types: 🌛 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.

What we need to know is that there are only three types of conversions in JS

  • To type Number:Number() / parseFloat() / parseInt()
  • To String:String() / toString()
  • Convert to Boolean:Boolean()

Both primitive and object types are 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, right

Converted to Boolean

☀️ Explicit: Boolean() methods can be used to explicitly convert values to Booleans.

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

Boolean(2)    // Display type conversion
if(2) {}      // Implicit type conversion is triggered by logical judgment!!!!!2           // Logical operators trigger implicit type conversions
2 || 'hello'  // Logical operators trigger implicit type conversions
Copy the code

Logical operators (such as | | and &&) is internally done Boolean type conversion, but actually returns the value of the original operand as, even if they are not a Boolean type.

// Return number of type 123 instead of Boolean true
// 'hello' and '123' are still internally converted to Boolean to evaluate expressions
let x = 'hello' && 123  // x === 123
Copy 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

Convert a string

The ☀️ explicit: String() method can be used to explicitly convert a value to a String.

String([1.2.3])    / / "1, 2, 3"
String({})    //"[object Object]"
Copy the code

🌛 implicit: Implicit conversions are usually triggered when there is the + operator and one of the operands is of type 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

Is converted to a number

The ☀️ explicit: Number() method can be used to explicitly convert a value to a numeric type.

  • String to number: The empty string becomes 0, and if any non-valid numeric character occurs, the result is NaN
Number("")           / / 0
Number("10px")       //NaN
Number("10")         / / 10
Copy the code
  • Boolean converts to a number
Number(true)         / / 1
Number(false)        / / 0
Copy the code
  • Null and undefined are converted to numbers
Number(null)         / / 0
Number(undefined)    //NaN
Copy the code
  • TypeError: Cannot convert a Symbol value to a number. TypeError: Cannot convert a Symbol value to a number
Number(Symbol())     //Uncaught TypeError: Cannot convert a Symbol value to a number
Copy the code
  • BigInt get rid of “n”
Number(12312412321312312n)     / / 12312412321312312
Copy the code
  • The following steps are followed to convert objects to numbers
  1. The object is called firstSymbol.toPrimitiveThis method, if this method doesn’t exist
  2. Then call the objectvalueOfGets the original value, if the value obtained is not the original value
  3. Then call the objecttoStringTurn it into a string
  4. Finally, the string is based onNumber()Method is converted to a number
let obj ={
    name:'xxx'
}
console.log(obj-10) // Math: convert obj implicitly to a number first, then perform the math
// Running mechanism
obj[Symbol.toPrimitive] //undifined 
obj.valueof() // {name:xxx}
obj.toString() // [object object]
Number ("[object object]") // NaN
NaN-10 // NaN 
Copy the code

🌛 implicit: 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

Implicit conversion rules on both sides of the == operator

If the two data types are different, convert them to the same type and then compare them. Note the following:

Object == string

Converts an object to a string

[1.2.3] = ='1, 2, 3'              //true
[1.2.3] [Symbol.toPrimitive]   //undefined
[1.2.3].valueOf()             / / [1, 2, 3]
[1.2.3].toString()            / / "1, 2, 3"
Copy the code

null/undefined

null= =undefined      //true
null= = =undefined     //false
//null/undefined is not equal to any other value
Copy the code

Object == object

Compare the heap memory address, the same address is equal

= = {} {}//false because addresses are compared
Copy the code

NaN

Other than that, if the two types don’t match, the rest is converted to a number and then compared

Things to watch out for

= = = {} + []0               // true[] + {} = = =0               // false

{} + []
/** * for the compiler, the code block does not return any value * then +[] becomes a forced conversion ToNumber * [] becomes '' via oPrimitive, and finally '' is converted to 0 **/ via ToNumber{}; + [];Copy the code

The last

Let’s look at the question at the beginning of this article

let result = 100 + true + 21.2 + null + undefined + "Tencent"+ + []null + 9 + false;
// The result should be?

1.First of all,100 + trueThe + hyphen exists on both sidesNumberType,trueTurn number for1, and the result is:101
2.101 + 21.2+ on both sides of the hyphenNumberType, the result of addition is:122.2
3.1222. + nullThe + hyphen exists on both sidesNumberType,nullTurn number for0, and the result is:122.2
4.1222. + undefinedThe + hyphen exists on both sidesNumberType,undefinedTurn number forNaN.NaNComputes with any data type forNaN, the result is:NaN
5.NaN + "Tencent"The + hyphen exists on both sidesStringType,NaNTurn the string for"NaN", string concatenation, the result is:"NaNTencent"
6."NaNTencent"The + [] + concatenator exists on both sidesStringType, [] goes to string"", string concatenation, the result is:"NaNTencent"
7."NaNTencent" + nullThe + hyphen exists on both sidesStringType,nullTurn the string for"null", string concatenation, the result is:"NaNTencentnull"
8."NaNTencentnull" + 9The + connector existsStringType,9Turn the string for"9", string concatenation, the result is:"NaNTencentnull9"
9."NaNTencentnull9" + falseThe + connector existsStringType,falseTurn the string for"false", string concatenation, the result is:"NaNTencentnull9false"
Copy the code

conclusion

If this article is helpful, please like it at 😯

If there are mistakes in the article, welcome to correct; If you have additional information, please leave a message.