English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript basic tutorial

JavaScript object

JavaScript function

JS HTML DOM

JS browser BOM

AJAX basic tutorial

JavaScript reference manual

JavaScript Type Conversion

Type conversion is a method of converting one data type to another.

In JavaScript, data types are used to classify a specific data type, determine the values that can be assigned to it, and the operations that can be performed on it.

JavaScript data types

In JavaScript, there are5Different data types can contain values:

  • string

  • number

  • boolean

  • object

  • function

There are3Types of objects:

  • Object

  • Date

  • Array

There is also2A data type that cannot contain a value:

  • null

  • undefined

The type of operator

The typeof operator can help you find the type of your variable.

The typeof operator returns the type of a variable or expression.

typeof ""  // Returns "string"
typeof "Vishal"// Returns "string"
typeof "42"// Returns "string" (the number within quotes is a string)
typeof 42  // Returns "number"
typeof true// Returns "boolean"
typeof false   // Returns "boolean"
typeof undefined   // Returns "undefined"
typeof null// Returns "object"
typeof {name:"Vishal", age:22} // Returns "object"
typeof [2, 4, 6, 8]// Returns "object" (not "array")
typeof function myFunc(){} // Returns "function"
Test and see‹/›

You can use the typeof operator to find the data type of a JavaScript variable.

Implicit Conversion

As a programming language, JavaScript is very tolerant of unexpected values. Therefore, JavaScript will try to convert unexpected values instead of rejecting them directly. This implicit conversion is called type coercion.

For example, in mathematical operations, values are automatically converted to numbers.

However, the result is not always as expected:

"3" + 2// Returns "32"  (because22,
"3" - 2// returns 1 (because “3" is converted to3)
"3" * "2"  // returns 6 (because "3" and "2" is converted to 3 and 2)
2 + true   // returns 3 (because true is converted to 1)
2 + false  // returns 2 (because false is converted to 0)
2 + null   // returns 2 (because null is converted to 0)
"2" + null // Returns "2null"  (because null is converted to "null")
Test and see‹/›

In some cases, we need to explicitly convert a value from one data type to another.

JavaScript provides many different methods to perform such data type conversion tasks.

In the following sections, we will discuss these methods in detail.

Convert the value to a string

We can convert the value to a string by callingString()Function orx.toString()Method, we will explicitly convert the value to a string.

By thisString()Function, we will convert the valuetruePass it as an argument to convert boolean values to strings:

String(true);// Returns "true"
Test and see‹/›

Additionally, we can pass a number to the function:

String(108);// Returns "108"
Test and see‹/›

We can use the typeof operator to check the type:

typeof String(true);// Returns "string"
typeof String(108); // Returns "string"
Test and see‹/›

We can use it in a similar wayx.toString()Method. We can replace x with a variable:

let temp = 108;
temp.toString();
Test and see‹/›

Alternatively, we can place the value in parentheses instead of using x.toString() for variable assignment:

(9048).toString();// Returns "9048"
(false).toString();   // Returns "false"
(50 + 20).toString(); // Returns "70"
Test and see‹/›

By usingString()orx.toString()We can explicitly convert values of Boolean or number data types to string values to ensure our code runs as expected.

Convert value to number

When converting values to the numeric data type, we will useNumber()Function.

First, we will convert the numeric text string to a number, but we can also convert boolean values.

We can pass a numeric string toNumber()Function:

Number("1992");// returns 1992
Test and see‹/›

We can also assign a string to a variable and then convert it:

let debt = "3500";
Number(debt); // returns 3500
Test and see‹/›

Space strings or empty strings will be converted to 0 (zero):

Number(" ");// returns 0
Number(""); // returns 0
Test and see‹/›

    Note that non-numeric strings will be converted to NaN, where NaN stands forNon-numericThis includes numbers separated by spaces:

Number("seventy");   // returns NaN
Number("Hello world");   // returns NaN
Number("12,000");// returns NaN
Number("5 7");   // returns NaN
Number("26-11-2008");// returns NaN
Test and see‹/›

For boolean data types,false'sis0,true'sis1:

Number(false);  // returns 0
Number(true);   // returns 1
Test and see‹/›

If the argument is a Date object, thenNumber()The function returns the number of milliseconds since 1970 years1month1milliseconds since the start of the day at midnight:

Number(new Date());
Test and see‹/›

TheNumber()The function converts non-numeric data types to numbers.

Convert values to boolean values

To convert a number or string to a boolean value, use the Boolean() function.

Any value interpreted as empty (such as the number 0, an empty string, or values such as undefined, NaN, or null) will be converted tofalse:

Boolean(0); // Returns false
Boolean("");// Returns false
Boolean(undefined); // Returns false
Boolean(NaN);   // Returns false
Boolean(null);  // Returns false
Test and see‹/›

Other values will be converted totrueincluding string literals consisting of spaces:

Boolean(50); // Returns true
Boolean(-50);// Returns true
Boolean(3.14);   // Returns true
Boolean("false");// Returns true
Boolean("Hello World");  // Returns true
Test and see‹/›

Note that "0" as a string literal is converted totrue,Because it is a non-empty string value:

Boolean("0");   // Returns true
Test and see‹/›

Converting numbers and strings to boolean values allows us to evaluate data within binary terms and can be used to specify streams within the program.

Convert an array to a string

toString()This method converts an array to a string of (comma-separated) array values.

var months = ["Jan", "Feb", "Mar", "Apr", "May"];
document.getElementById("result").innerHTML = months.toString();
Test and see‹/›

join()This method also converts all elements of the array to a new string.

The behavior of this method is similar totoString()However, you can also specify a delimiter.

var fruits = ["Banana", "Apple", "Mango"];
fruits.join(" + ");   // Banana + Apple + Mango
fruits.join(" / ");   // Banana / Apple / Mango
fruits.join(" © ");  // Banana © Apple © Mango
Test and see‹/›

When expecting the original value, JavaScript automatically converts the array to a comma-separated string.

When you try to output an array, it is always like this.

let fruits = ["Apple", "Mango", "Banana", "Orange"];
document.getElementById("result").innerHTML = fruits;
Test and see‹/›

Convert a string to an array

split()method to split the string into an array of substrings and then return the new array.

We will usesplit()The method splits the array by using the space character represented by " ".

var str = 'Air Pollution is introduction of chemicals to the atmosphere.';
var arr = str.split(" ");
Test and see‹/›

Now we arearrA new array has been added to the variable, and we can access each element using an index:

arr[0];   // Air
arr[2];   // is
Test and see‹/›

In the following example, we will use "i" as a delimiter:

var str = 'Air Pollution is introduction of chemicals to the atmosphere.';
var arr = str.split("i");
Test and see‹/›

If an empty string ("") is used as a delimiter, the string will be converted to a character array:

var str = 'Air Pollution is introduction of chemicals to the atmosphere.';
var arr = str.split(
Test and see‹/›