Midnight eleven o ‘clock, brush circle of friends, suddenly brush to such a picture, heart: how, my JS fierce manual funny.

However, after I carefully read all the JS statements, I found myself still have several unknown reasons…. Emmmm, I’m not the only one!

Look, do not know the reason for most of the JS type conversion related problems, so we understand the JS type conversion related content.

To understand these odd answers, we need to understand the difference between strong/weak typing and dynamic/static typing in a programming language

Programming language strong and weak type, dynamic type, static type difference

Strong and weak type

Strong and weak typing means that in computer science and programming, we often classify the type systems of programming languages as strongly typed and loosely typed. These terms are not well defined, but are used to describe how programming languages treat values mixed with different data types. Strongly typed languages often fail directly or compile when the argument type of a function does not match the actual call type. Weakly typed languages, on the other hand, often perform implicit conversions or produce unexpected results. — wikipedia

Strongly typed Weak type
Popular accounts A language that enforces data definition.

If a variable is specified with a data type, the data type is immutable until cast.
The distinction between data types can be ignored. In contrast to strong typing, a variable can be assigned different data types.
Is it safe security unsafe
language C/ C++ / C# / JAVA PHP / ASP/ JavaScript / Python
🌰 Integer division cannot be used on strings 1 + ‘2’ = 12
the Rigor can avoid some problems The code is concise, does not need to pay attention to the type of variable, flexible
The disadvantages Writing tedious There will be some potential potholes

Static/dynamic type

Dynamic programming language is a category of high-level programming language, which has been widely used in computer science. It is a language whose structure can be changed at run time: for example, new functions, objects, and even code can be introduced, existing functions can be deleted, or other structural changes can be made. Dynamic languages are very dynamic right now. The well-known ECMAScript (JavaScript) is a dynamic language, in addition to PHP, Ruby, Python and other dynamic languages, while C, C++ and other languages are not dynamic languages. — wikipedia

Type division of common languages

Because strongly typed languages typically run a type detection system at runtime, strongly typed systems are generally slower than weakly typed languages. Dynamic typing is also slower than static typing.

So theoretically C, Java, JS, and Python should run at C > Java > JavaScript > Python

JS data type

I just said that JavaScript is a ** weakly typed ** language. This means that you don’t have to declare the type of the variable in advance; the type will be determined automatically as the program runs. This also means that you can use the same variable to hold different types of data.

let a = 123
a = 'abc
a = () => {}

Copy the code

The latest ECMAScript standard defines eight data types:

  • Seven kinds ofThe original type:
    • Boolean
    • Null
    • Undefined
    • Number
    • BigInt
    • String
    • Symbol
  • And the Object

There are a few points to note here:

  • According to the ECMAScript standard, there is only one numeric type in JavaScript: values in the double precision 64-bit binary format (-(2-1) to 2-1) based on the IEEE 754 standard. It does not give a specific type for integers.
  • Some signed values:+Infinity.-Infinity 和 NaN(Non-numeric, Not a Number) are Nubmer types.
  • Only one integer in a number type can be represented in two ways: 0 can be represented as -0 or +0 (“0” is short for +0)
  • Objects, arrays, Data, and re are all objects
  • typeof null === 'objectIn the original implementation of JavaScript, values in JavaScript were represented by a tag representing a type and actual data values. The type label of the object is 0. Due to thenullRepresents a null pointer (0x00 on most platforms), so null’s type label is 0,typeof nullAnd therefore return"object".
typeof {a: 1} = = ='object';

typeof [1.2.4= = ='object';

typeof new Date() = = ='object';

typeof /regex/ === 'object';

// This has been true since the beginning of JavaScript
typeof null= = ='object';
Copy the code

JS type conversion

So, if we want to convert a value from one type to another, we need a type conversion.

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

Display type conversion

Display type conversion is relatively simple, through some functions provided by JS, can be directly converted

  • intoNumberType:Number() / parseFloat() / parseInt()
  • intoStringType:String() / toString()
  • intoBooleanType:Boolean()

There are a few points to note here:

  • The toString() method defined by the Number class can accept an optional argument representing the conversion cardinality; if this parameter is not specified, the conversion rule will be based on decimal.

  • Object to string conversion in js goes through the following steps:

    • This method is called if the object has a toString() method. If it returns a primitive type value, JS converts the value to a string and returns the string.
    • If the object does not have a toString() method, or if the method does not return a primitive type value, then the valueOf() method is called. If this method exists, it is called, if the return value is a primitive type value, converted to a string and returned
    • Otherwise, JS cannot get a primitive type value from toString() or valueOf(), and a type error exception will be thrown
  • Undefined, null, false, +0, -0, NaN, “” Only these toBoolean() are false, the rest are true

  • The toString() method defined by the Number class can accept an optional argument representing the conversion cardinality; if this parameter is not specified, the conversion rule will be based on decimal.

ToPrimitiveConverts a value to its original value

One more method, which I’ll use later, is ToPrimitive, which converts the received parameter to the original type:

ToPrimitive(data, PreferredType?)
Copy the code

The input is the value to convert, the PreferredType is an optional parameter, and the ToPrimitive operator converts its value parameter to a non-object type. If the object has the ability to be converted to more than one primitive type (taking the number string argument), the optional PreferredType can be used to select the type.

When ToPrimitive(data,preferredType) is executed, if the second parameter is null and data is a Date instance, the preferredType is set to String. Otherwise the preferredType will be set to Number

If the preferredType is Number, ToPrimitive performs the following operations: 1. If data is a raw value, return it; 2. Otherwise, call data.valueof () and return the original value if the result is executed. 3. Otherwise call data.tostring () and return it if the result is the original value; 4. Otherwise, an exception is thrown.

If the preferredType is String, swap steps 2 and 3 above, i.e. If data is a raw value, return it; 2. Otherwise, call data.tostring () and return it if the result is the original value; 3. Otherwise, call data.valueof () and return the original value if the result is executed. 4. Otherwise, an exception is thrown.

Implicit conversion

This brings us to the focus of this article, JS implicit conversion. It’s also a place that pits countless front ends.

JS implicit conversions mainly involve two operators, + and ==

One yuan+Operator, unary – operator

The unary + operator converts to Number if it is followed by Number, which makes no difference.

But if it is not followed by a Number, the ToNumber method is called.

// String
const a = '123'

typeof a
"string"
const b = +a

typeof b
"number"

// Object
const c = {}

typeof c
"object"
const d = +{}

typeof d
"number"

d
NaN
Copy the code

Addition operator



ToPrimitive

Note clause 7, that is, return the concatenated String after toString() if the left or right side of the expression is String

` 1 + '1' "11"Copy the code

[] + {} = [object object]

= =Abstract and other operators

It is mainly divided into the same type and different type of X and y. The type is the same and there is no type conversion. The type is different

  • If x or y is null, undefined // returns true
  • If x and y are Number and String, the value is converted to Number for comparison.
  • When there is a Boolean type, the Boolean is converted to a Number type comparison.
  • An Object, a String, or a Number, that converts Object primitives (ToPrimitive), then compare the original values according to the above procedure.

So far, the beginning of the graph in addition to 2, 3, 4, 5 questions of the answer can be found in this article, I believe that smart you carefully read this article must master the JS type conversion related knowledge, try to analyze the reasons for the other several problems down to test their mastery of it!