Let’s start with a graph to see the differences between weakly typed, strongly typed, dynamically typed and statically typed languages.

Strong (data) typed languages

Definition: Once a variable is assigned a data type, it is always of that data type unless cast. For example, if you define an integer variable a, we cannot treat a as a string.

Weak (data) typed languages

Q: Can you describe why javascript is a weakly typed language?

Where is the weakness? Where is it reflected?

When JavaScript declares variables, there is no pre-determined type (just var). The type of a variable is the type of its value, meaning that the current type of a variable is determined by its value. The fact that weak typing does not require pre-typing is both convenient and frustrating. To take full advantage of this feature, you must understand the principles of type conversion.

Example 1:

var a = 1 + '2'; // The value of a outputs 12, which would be an error in strongly typed languages
Copy the code

Example 2:

We var an A (whose type is determined by the value assigned to the equals sign), and we can change a as we like below

var a = 0; 
console.log(typeof a);// number
a = true;
console.log(typeof a);// boolean
a = '12';
console.log(typeof a);// string
Copy the code

Wait, wait, wait…

Explicit (strong) type conversion

Number()

Let’s look at an example:

Number(undefined),		//NaN
Number(null),			/ / 0

Number(true),			/ / 1
Number(false),			/ / 0

Number(' '),			/ / 0
Number(' '),			/ / 0

Number('12'),			/ / 12
Number('012'),			/ / 12
Number('0xff90'),		/ / 65424
Number('5e5'),			/ / 500000
Number('k'),			//NaN

Number({}),			//NaN
Number(function(){}),	        //NaN
Number([]),			/ / 0
Number([' ']),			/ / 0
Number([2]),			/ / 2
Number(['2']),			/ / 2
Number([2.3]),			//NaN
Copy the code

From the above example we can derive the conversion rule for the Number operator:

  • Undefined is converted to NaN
  • Null is converted to 0
  • True converts to 1 and false converts to 0
  • string
    1. The space string is converted to 0
    2. A non-empty string whose contents are pure numbers (including base and scientific notation) converted to corresponding numbers
    3. The rest are nans, for exampleNumber (' funcation () {} ') or Number (' AB ')
  • Numbers convert to numbers themselves
  • Object (reference type)
    1. If it is an object {}, a function, then it is converted to NaN

    2. An empty array is converted to 0, there is only one data in the array and that data can be converted to a number, then it is converted to the corresponding number, and everything else is converted to NaN

String()

String(null),		 //'null'
String(undefined)        // 'undefined'

String(1)                / / '1'
String(-1)               // '-1'
String(0)                / / '0'
String(-0)               / / '0'

String(Infinity)         // 'Infinity'
String(-Infinity)        // '-Infinity'
String(true)             // 'true'
/* Reference type */
String([1[2]]),	 / / '1, 2,'
String([1[2.3]])        / / '1, 2, 3'
String(['koala'.1])      // 'koala,1'
String(function(){}),	 // 'function(){}'
String({}),		 // '[object Object]'

String(Math.pow(1000.10))// '1e+30'
String(new Date())       "Thu Jul 04 2019 10:07:58 GMT+0800"
Copy the code

From the above example we can derive the conversion rules for the String operator:

  • The result of primitive data types, null, and undefined is to enclose data in quotes as strings
  • Reference data type
    1. If it is an array, the result is to remove all the brackets and enclose them in quotes

    2. If it is an object, the result is ‘[object object]’ (except for the date object)

    3. In the case of a function, the result is a quotation mark around the whole function

Boolean()

Boolean(undefined)          // false
Boolean(null) 		    // false
Boolean(0)		    // false
Boolean(NaN)                // false
Boolean(' ')                 // false

Boolean(' ')                // true
Boolean({})                 // true
Boolean([])                 // true
Boolean(!NaN)               // true
Boolean(new Boolean(false)) // true
Copy the code

From the above example we can derive the Boolean operator conversion rule:

All values are true except the following six:

  1. undefined

  2. null

  3. Minus 0 or 0 or plus 0

  4. NaN

  5. “(empty string)

Here’s an extra point Truthy:

In JavaScript, truthy refers to a converted value that is true in the context of a Boolean value. All values are true unless they are defined as false (that is, true except false, 0, “”, NULL, undefined, and NaN).

The following is an example of a true value in JavaScript (which will be converted to true and the code snippet after if will be executed) :

if (true)
if ({})
if ([])
if (42)
if ("foo")
if (new Date())
if (-42)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)
Copy the code

What is the principle behind the three conversions?

The principle behind the transformation

In JavaScript every object has a valueOf() and toString() method

ValueOf () returns the original valueOf this object

Many of JavaScript’s built-in objects (Array, Function, String, Boolean, Number) have overridden this Function to better suit their functional needs. Therefore, the return value and return value type of the valueOf() method for different types of objects may differ.

object The return value
Array Returns the array object itself.
Boolean Boolean value.
Date The stored time is millisecond UTC from midnight on January 1, 1970.
Function The function itself.
Number A numeric value.
Object The object itself. This is the default.
String String value.
Math and Error objects do not have valueOf methods.

ToString returns the string representation of an object

Each object has a toString() method, which is called automatically when the object is represented as a text value or when the object is referenced as a desired string.

Keep in mind that valueOf() and toString() will call themselves in certain situations.

object The return value
Number Data converted to a string form, such as ‘123’
Boolean Convert data to a string form, e.g. ‘true’, ‘false’
String Data converted to a string form, such as’ JSLDKFJSL ‘
Function Put quotes around the data, such as: ‘function foo(){}’
Object “[object Object]”
Date “Thu Jul 04 2019 11:53:31 GMT+0800 “Current time

The principle behind the Number method

  1. Call the valueOf method of the object. If the value of the original type is returned, the Number function is used without further steps.
  2. If the valueOf method does not return the original value, the toString method is called.
  3. The toString method returns a value of the original type, and the Number function is used on that value without further steps.
  4. iftoStringMethod returns still afternotOriginal value, an error is reported and thrownTypeError Exception (usually not present)

The principle behind the String method

  1. Calls the toString method of the object. If the value of the original type is returned, the String function is used and no further steps are required.
  2. If the toString method returns something other than the original value, the valueOf method is called.
  3. The valueOf method returns a valueOf the original type, and the String function is used for that value without further steps.
  4. ifvalueOfMethod returns still afternotOriginal value, an error is reported and thrownTypeError Exception (usually not present)

Note: They are called in reverse order

Implicit type conversion

/* Implicit type conversion (+ - * / %); /* Implicit type conversion (+ - * / %); /* Implicit type conversion (+ - * / %) 2. Unary +- (+ / -); 3. Some comparison operators */
console.log(
    Number({1: 2}),
    [] + {}, 					// '[object, Object]'{} + [].// '[object, Object]'
    [] + function(){}, 			// "function(){}"
    2 + [2.3]./ / '22, 3'
    10 + function(){}, 			// "10function(){}"
    null + undefined.// NaN
    [] - 5./ / - 5
    '6' * [], 					/ / 0
    null % true.// 0%1 === 0
    true / [7].// 1/7 === 0.14285714285714285
    'a'-'b'						//NaN-NaN=NaN
    'A' - 'A' + 2.// NaN
    1+undefined.//NaN
    1+null./ / 1
    3+'6'./ / the '36'
    2+ []./ / '2'
    2+ {a:12},			//'2[object Object]'
    3+ {},//'3[object Object]'{} +3				//'[object Object]3'
);
// The comma operator outputs the last parenthesis
console.log(1.2.3);		/ / 1 2 3
console.log((1.2.3));	/ / 3


Copy the code

== implicit conversion on both sides

/* Why '12' == 12? We know that equals true, but how does that work? 1. When both sides of the == sign are primitive data types, both sides are implicitly converted to the Number(mix) */
console.log(
    '12'= =12.0= =' '.1= =true.2= =false.'true'= =true.' '= =false,!!!!!NaN= =false
);

console.log(
    undefined= =0.undefined= =' '.undefined= =false.undefined= =undefined.// true
    null= =0.null= =' '.null= =false.null= =undefined // true
)
/ * 2, if there are an object on both sides of the = =, * /
console.log(
    [1] = =1And [] = =0[1] = =true[1.'a'.3] = ='1,a,3'And [] = =undefined,
    {a: 1} = =1[null] = =null
)
Copy the code

Comma operator

console.log((1.2.3)); / / 3


/ / title:
var a = 10, b = 20;
function fn(){
    return a++, b++, 10;
}
console.log(a, b, fn());
var c = fn();
console.log(a, b, c);
/ / interpretation:
Copy the code

Reference:

  • Do you really know JavaScript data types?
  • MDN