SoFunction
Updated on 2025-04-07

JavaScript implicit type conversion code example

Data type conversion between value types:

(1) Use the + operator for numbers and strings:

If the number and string are operated using the + operator, the number will be converted to a string first, and then the string concatenation operation will be performed:

var str = "string text ";
var num = 10;
(str + num) // "string text 10"

(2) + operator operation participating in Boolean value:

If there is Boolean participation, the Boolean value will first be converted into the corresponding number or string, and then the corresponding string concatenation or arithmetic operation will be performed.

var num = 12;
var bool = true;
var str = "text";
(num + bool) //13
(str + bool) // "text true"

(3) + operator operation involved in Null and Undefined

If calculated with the number, null will be converted to 0, undefined will be converted to NaN

Note: Null is converted to 0, Undefined is converted to NaN

(undefined + 1) //NaN
(null + 1) // 1

First call the string() method, obtain the corresponding string value and then perform the operation

var a;
var str='123';
(a + str);//'undefined123'
var a=null;
var str='123';
(a + str);//'null123'

(4) ==Equiliative operation:

Undefined and null are more special. The return value of both of them is true using the == operator.

When comparing other value types (Number, Boolean, Null, Undefined) they will convert the operation into numbers.

(undefined == null); // true
("1" ==true); //true

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.