Type conversion

In most cases, operators and functions automatically convert the values assigned to them to the correct type.

For example, Alert automatically converts any value to a string for display. Arithmetic operators convert values to numbers.

In some cases, we need to explicitly convert the value to the type we expect.

The object has not been included in the discussion

The Object type is not discussed in this chapter. We’ll start with primitive types, and then we’ll start with object types. We’ll learn about object conversions in the Info: Object-Toprimitive section.

String conversion

When we need a value in the form of a string, a string conversion takes place.

For example, alert(value) converts the value to a string type and displays the value.

We can also explicitly call String(value) to convert value to a String type:

let value = true;
alert(typeof value); // boolean

value = String(value); // Now the value is a string of "true"
alert(typeof value); // string
Copy the code

String conversions are the most obvious. False becomes “false”, null becomes “null”, etc.

Digital conversion

In arithmetic functions and expressions, number type conversions are performed automatically.

For example, when division/is used for non-number types:

alert( "6" / "2" ); // 3, the string value is automatically converted to number and evaluated
Copy the code

We can also explicitly convert this value to type Number using Number(value).

let str = "123";
alert(typeof str); // string

let num = Number(str); // Change to number type 123

alert(typeof num); // number
Copy the code

When we read a value from a string source, such as a text form, but expect a number, an explicit conversion is often required.

If the string is not a valid number, the result of the conversion is NaN. Such as:

let age = Number("an arbitrary string instead of a number");

alert(age); // NaN, conversion failed
Copy the code

Number type conversion rule:

value Become a…
undefined NaN
null 0
True and false 1 and 0
string The number contained in a purely numeric string with the leading and trailing Spaces removed. If the remaining string is empty, the result is converted to0. Otherwise, the number is “read” from the rest of the string. Returns if a cast error occursNaN.

A string can be converted to number only if the string consists of Spaces and numbers, except for undefined, null and Boolean. Otherwise, NaN will be returned with error.

Example:

alert( Number("123"));/ / 123
alert( Number("123z"));// NaN (error reading "z" from string)
alert( Number(true));/ / 1
alert( Number(false));/ / 0
Copy the code

Note that null and undefined are a little different here: null becomes the number 0, and undefined becomes NaN.

The plus ‘+’ connection string

Almost all arithmetic operators convert values to numbers for operation, with the exception of the plus sign +. If one of the operands is a string, the other one is also converted to a string.

Then, connect the two together:

alert( 1 + '2' ); // '12' (string to the right of the plus sign)
alert( '1' + 2 ); // '12' (string to the left of plus sign)
Copy the code

This only happens if at least one of them is a string. Otherwise the value is converted to a number.

Boolean conversion

Boolean conversions are the simplest.

It happens in logical operations (we’ll get to conditional judgments and other things like that later), but it can also be explicitly transformed by calling Boolean(value).

The conversion rules are as follows:

  • A value that is intuitively “empty” (e.g0, empty string,null,undefinedNaN) will befalse.
  • The other values becometrue.

Such as:

alert( Boolean(1));// true
alert( Boolean(0));// false

alert( Boolean("hello"));// true
alert( Boolean(""));// false
Copy the code

Note: string containing 0"0"true

Some programming languages, such as PHP, treat “0” as false. But in JavaScript, non-empty strings are always true.

alert( Boolean("0") ); // true alert( Boolean(" ") ); // Blank, also true (any non-empty string is true)Copy the code

conclusion

There are three common conversions: to string, to number, and to Boolean.

String conversions — Conversions occur when output content, and can also be explicitly converted via String(value). String conversions of primitive values are usually obvious.

Numeric conversions — Conversions occur when arithmetic operations are performed, and can also be explicitly converted by Number(value).

Digital conversions follow these rules:

value Become a…
undefined NaN
null 0
true / false 1/0
string “Read as is” string, whitespace at both ends is ignored. The empty string becomes0. Error conversion outputNaN.

Boolean conversions — Conversions occur when logical operations are performed. Explicit conversions can also be performed through Boolean(value).

Boolean conversions follow the following rules:

value Become a…
0.null.undefined.NaN."" false
Other values true

Most of the rules above are easy to understand and remember. Here are some notable examples of how people usually make mistakes:

  • rightundefinedWhen performing the digital conversion, the output isNaNRather than0.
  • right"0"And whitespace only strings (for example:""When Boolean conversion is performed, the output istrue.

We did not cover object conversions in this summary. After we have learned more about JavaScript basics, we will cover object type conversions in the section on Object Primitives.

Homework assignments

Do the questions yourself and then look at the answers.

Type conversion

Importance: ⭐️⭐ ⭐️⭐️

What are the results of the following expressions?

"" + 1 + 0
"" - 1 + 0
true + false
6 / "3"
"2" * "3"
4 + 5 + "px"
"$" + 4 + 5
"4" - 2
"4px" - 2
7 / 0
"9" + 5
"9" - 5
null + 1
undefined + 1
" \t \n" - 2
Copy the code

Think about it, write them down and compare them with your answers.

The answer:

Reply 1-2-6 in the background of wechat public account “Technology Talk” to obtain the answer to this question.


Modern JavaScript Tutorials: Open source modern JavaScript tutorials from beginner to advanced quality. React provides a JavaScript tutorial for MDN learners.

Read for free online: zh.javascript.info


Scan the QR code below and follow the wechat public account “Technology Chat” to subscribe for more exciting content.