DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Adding Two Hours in DataWeave: Mule 4
  • What's New in Mule 4.4 - With Example
  • From Zero to Meme Hero: How I Built an AI-Powered Meme Generator in React
  • DataWeave: Play With Dates (Part 1)

Trending

  • Testing SingleStore's MCP Server
  • Integrating Security as Code: A Necessity for DevSecOps
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  1. DZone
  2. Coding
  3. JavaScript
  4. JavaScript Type Conversion and Coercion

JavaScript Type Conversion and Coercion

The type conversion of variables in JavaScript takes place both manually and explicitly; we just have to write the function name or method manually. Read more.

By 
Bikash Jain user avatar
Bikash Jain
·
Jan. 16, 23 · Review
Likes (1)
Comment
Save
Tweet
Share
2.8K Views

Join the DZone community and get the full member experience.

Join For Free

The type conversion of variables in JavaScript takes place both manually and explicitly; we just have to write the function name or method manually. This is known as explicit type conversion, while type coercion in JavaScript is the process of implicit conversion of the variables data types in JavaScript.

Type conversion in TypeScript can either be implicit (this is automatically done during the code execution) or explicit (this is done by the developer). The TypeScript file will check for errors after converting the code from JavaScript to TypeScript, as TypeScript has strict type-checking.

As we know, type conversion in JavaScript refers to the process of explicitly type conversion in JavaScript; we know that there are five data types in JavaScript, namely String, number, boolean, object, and function. But we can use type conversion in only three of them they are number, string, and boolean. 

In TypeScript, there is both the double equality operator (==, which is called the loose equality operator) and the triple equality operator (===, which is called the strict equality operator). We use both operators to compare the values’ equality.

Now let us see read about the different processes with their respective methods in TypeScript.

Converting to Strings

In this method, the number type is converted into string data type in JavaScript.

Let us see this with the help of an example:

  1. String(): Whatever we write inside the String(), irrespective of any datatype, the data type gets converted to string type.
    Let us see first see the syntax followed by an example:

JavaScript
 
String(n)


Here the n within brackets refers to the value to be converted into a string.

Now let us implement the syntax in an example:

JavaScript
 
String(1520)

String(1234)


Output

JavaScript
 
"1520"

"1234"


In the above code, we have converted the values from numbers to a string by writing the value inside the string syntax. Run the above code in your editor for a better and clear explanation.

In string conversion, there are some methods. They are namely:

  • toexponential()
  • toprecison()
  • tofixed()

Now let us read about the use of each method in detail with the help of examples:

toexponential()

This JavaScript method converts the numeric value into a rounded string symbol.

Let us see first see the syntax followed by an example:

JavaScript
 
n.toExponential()


Here the .toEponential method is used to convert into string exponential form (e+number)…

You can learn more about the same here.

Now let us implement the syntax in an example:

JavaScript
 
let n=12.654;

console.log(n.toExponential());


Output

JavaScript
 
let n=12.654;

console.log(n.toExponential());


In the above example, we have taken a number input, then we have printed it in its exponential form, the data type of which is a string.

toFixed()

This method converts the number to a string of fixed length, which we provide:

Let us see first see the syntax followed by an example:

JavaScript
 
n.toFixed()


Here the .toEponential method is used to convert the number into its string-fixed form.

Now let us implement the syntax in an example:

JavaScript
 
let n=152.9054;

console.log(n.toFixed());

let n1=69.156;

console.log(n1.toFixed(2));


Output

JavaScript
 
152

69.15


In the above example, we have converted the above number into a string, and by using the .toFixed method, we have just mentioned the number of digits we want to print after the decimal; that is, if we do not mention anything, then by default, the user will consider it as zero and will not print anything after the decimal. Run the above code in your editor for a better and clear explanation.

toPrecison()

It is used to print the numbers after the decimal point, the data type of which is a string.

Let us see first see the syntax followed by an example:

JavaScript
 
n.toExponential()


Here the .toEponential method is used to convert into string exponential form (e+number)…

Now let us implement the syntax in an example:

JavaScript
 
let n=12.654;

console.log(n.toFixed());

let n1=18.124;

console.log(n1.toFixed(1));


Output

JavaScript
 
12.654

18.12


In the above example, we have first taken a number (n) as input, then used the .toFixed() function, we have printed the number to its fixed from in string. In the fixed function, if we do not mention anything inside the optional parameters, then it will consider it as zero and will print the entire value. If we mention any number in the optional parameter brackets, then it will just exclude the count of values from the decimal part and will print the rest part of the converted string.

To Number Type Conversion

In this method, we will see how to convert a string to a number data type with the help of various built-in types.

The number conversion methods are as follows:

  1. number()
  2. parseFloat()
  3. parseInt()

Now let us read about each of them in detail:

1. number()

In this method, we simply convert a string value and boolean values to a number data type.

Let us see first see the syntax followed by an example:

JavaScript
 
Number(n)


Here the Number method is used to convert the (n), which may be either string or boolean value, into a number data type.

Now let us implement the syntax in an example:

JavaScript
 
Number('123');

Number('1520');

Number('5969');

Number(actual);// true in numeric form is 1 while false in numeric form is 0


Output

JavaScript
 
123

1520

5969

1


We have explicitly converted the values from string or boolean data type to number data type by writing the Number() function. Run the above code in your editor for a better and clear explanation.

2. parseInt()

It is used to convert only the numeric string values to string, with the condition that the first part must be of numeric type.

Syntax::

JavaScript
 
parseInt(numeric_stringpart,radixpart)


Example:

JavaScript
 
parseInt(1520nlcdj)

parseInt('qwer@12222')


Output

JavaScript
 
1520

Nan


In the second output line, the output will be Nan because it did not meet the condition that the first part must be of numeric type.

3. parseFloat()

It is used to convert the string to its floating point number.

Let us look at the syntax below, followed by an example:

JavaScript
 
parseFloat(n)


Here n is the variable that will be converted into a number data type.

Example:

JavaScript
 
parseFloat('126.7655')


Output

JavaScript
 
126.7655


We have converted the string into its parent numeric form in the above example.

To Boolean Type Conversion

In this, we will convert the values from numeric type to boolean type.

Syntax:

JavaScript
 
Boolean(n)


Here the n within brackets value will be converted to boolean type.

Now lets us see an example:

JavaScript
 
Boolean(1520)

Boolean(' ')

Boolean('yash')

Boolean(null)


Output

JavaScript
 
true

true

true

false


Run the above code in your editor for a better and clear explanation.

Type Coercion in JavaScript

Type coercion is type conversion itself but the type conversion done here is implicit; both conversion and coercion are the same, the only difference being implicit and explicit type conversion. 

The type coercion is also used in the same data types: numbers, string, and boolean values. As we all know, TypeScript is a superset of JavaScript itself, so any valid JavaScript code is valid TypeScript code.

Type coercion in TypeScript just only coerces to the string, number, and Boolean primitive types as in type conversion. There’s no way in TypeScript that we can coerce a value type to an object or function.

TypeScript has two characterized forms of coercion they are implicit coercion and explicit coercion.

Now let us see how to perform type coercion in each of these types:

To String Coercion

It is used to convert the non-string value to the string type.

Let us understand this with the help of an example:

JavaScript
 
console.log('15'+20);

console.log('29'+null);

console.log(50+'45'+null)


Output

JavaScript
 
'1520'

'29null'

'5045null'


The string coercion is performed using the + operator in JavaScript. Hence, if we use the + operator with any string, it will be converted to string type.

To Number Coercion

Using mathematical operators with variables then, we can convert any non-numeric type to a numeric type. However, we cannot use the + operator in numeric coercion.

Let us understand this with the help of an example:

JavaScript
 
console.log('34'-34);

console.log('6'*8);

console.log('45'/45);

console.log('15'%5);


Output

JavaScript
 
0

48

1

0


Here we are converting the non-numeric values to numeric values using mathematical operators; we can just not use the + operator. Run the above code in your editor for a better and clear explanation.

To Boolean Coercion

In this type of connection, the boolean values are converted into mathematical values.

Let us understand this with the help of an example:

JavaScript
 
console.log(false-5);

console.log(true+5);


Output

JavaScript
 
-5

6


Since we know that the value of true in numeric terms is one while the value of false in numeric terms is zero, we can calculate according to it.

Conclusion

  • Type conversion and type coercion are the same things just. However, there is a difference between implicit and explicit type conversion.
  • Both type conversion and type coercion work on only number, string, and boolean data types.
  • Type conversion is very important in javascript as it helps us to convert the types whenever we need it.
  • Type conversion and coercion in TypeScript, in simple terms, just means the changing of the data type of a value to another data type like an integer type to string type, Boolean type into String type, etc.
  • The major difference between implicit and explicit type conversion is that the implicit conversions are automated by the JavaScript compiler behind the scenes, while explicit ones are done manually by us.
JavaScript Type conversion Strings Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Adding Two Hours in DataWeave: Mule 4
  • What's New in Mule 4.4 - With Example
  • From Zero to Meme Hero: How I Built an AI-Powered Meme Generator in React
  • DataWeave: Play With Dates (Part 1)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!