What is type conversion in JavaScript? Full Guide 2022
In JavaScript, type conversion is a technique that allows us to change the data types of a function from one to another. In some cases, the Javascript compiler does these conversions automatically, ensuring that the function receives valid inputs based on the operator used. In this essay, we’ll delve deeper into the subject and discover more about these conversions.
Introduction
JavaScript is one of the most used languages when it comes to building web applications as it allows developers to wrap HTML and CSS code in it to make web apps interactive. It enables the interaction of users with the web application. It is also used for making animations on websites and has a large community on GitHub. JavaScript has tons of libraries, one of which is React which we will be covering in this article later.
Use cases:
- Building web server and its interactive functions
- Animations and graphics, adding special effects to web components
- Validating forms and exception errors
- Adding behavior and functionalities to web pages
In JavaScript, promises are used to handle asynchronous operations. When dealing with several asynchronous activities, where callbacks might cause callback hell and unmanageable code, they are simple to manage.
The following terms are defined in this article:
- JavaScript’s Type conversion.
- The intrinsic rationale of these conversions is explained.
- We’ll also learn about type conversion in JavaScript, including its types, relevance, and implementation.
- The implementation of type conversions in any language other than JavaScript is not shown in this article.
Introduction to JavaScript’s type conversion
To begin with type conversions, we must understand that any computation may only be performed between data types of the same type. So, what if we force JavaScript to perform any of these actions, such as adding a number to a string? In such circumstances, the javascript compiler changes the number to string format by default and then concatenates the two, which is what type conversions are.
What is type conversion?
In JavaScript, type conversion is the conversion of one data type to another (for example, a string to a number, an object to a boolean, and so on) that is required for a function or operator to work correctly and produce the intended results.
When performing operations with distinct data types, type conversions are required. These conversions can be performed automatically by the javascript compiler or manually by us.
Let’s look at a few examples to better understand these conversions:
// Number is converted into String
console.log('5' + 3); // '53'
// String is converted into Number for calculation
console.log('5' - 3); // 2
console.log('5' * 3); // 15
// expression is converted into boolean
console.log(null == 1); // false
// When the result is not a number
console.log('Ale' - 2021); // NaN
Code language: JavaScript (javascript)
Because we’re working with distinct data types in the previous example, the javascript compiler, by default, turns a string to a number when we use them -, *, and / operators, while the + operator changes a number to a string.
If the conversion is required, the loose equality == operator performs it, like in the third example, where null is changed to 0 first and then the comparison phrase is 0 == 1, which is false.
Also, when there is no legitimate operation, as in the previous example, the javascript compiler turns the output of the expression into a number that is Not a Number, and the developer console displays NaN.
Types of type conversion
In Javascript, there are various types of type conversions.
In Javascript, there are two types of type conversions: implicit and explicit type conversions.
- Implicit type conversions – The javascript compiler performs type conversions automatically.
- Explicit type conversions – We perform manual type conversions.
Any data type, whether primitive or object, can be transformed into these three kinds. The logic underlying primitives and objects differ, but both primitives and objects can only be converted into these three types:
to boolean from string to number
Let’s start with type conversion in Javascript, both implicit and explicit.
Important points to remember in JS:
It is a scripting language |
It has unstructured code |
It is a programming language |
It is used both client-side and server-side to make web apps interactive |
It is built and maintained by Brendan Eich and the team |
Uses built-in browser DOM |
Extension of JavaScript file is .js |
Type conversion that is not explicit
For the operators or functions to work correctly, implicit conversions are conversions of one data type into another data type (ensuring that operations are performed among the same data types). In Javascript, these conversions are referred to as type coercion.
These conversions typically occur when you apply operators to values of various kinds, such as ‘2’ * 5, 1 == null, null == new Date(), or when external context, such as if(value)…, where value is coerced to a boolean, is invoked.
Type conversions that are explicit
Explicit conversions are type conversions that are performed manually in the source code by the developer in order to obtain the desired changes and erase the errors caused by implicit type conversions. In JavaScript, these conversions are known as typecasting.
Most Frequently Converted Data
Type conversions are an important component of JavaScript since the language has a lot of flexibility and the ability to convert one data type to another. The following are the many types of type conversion in JavaScript:
- Conversions of strings
- Conversions of numbers
- Boolean transformations
- Conversions of symbols
Converting Strings
String Conversion is the process of converting a data type into a string. The String() method can be used to directly convert a data type to a string, and the + binary operator can be used to initiate implicit string conversion when one operand is a string.
// String Conversion Implicitly
"25" + 56; // '2556'
"25" + null; // '25null'
"Ale " + undefined; // 'Ale undefined'
"25" + false; // '25fasle'
// String Conversion Explicitly
String(23); // '23'
String(true); // 'true'
String(32 - false); // '32'
String(32 - true); // '31'
Code language: JavaScript (javascript)
Converting Numbers
Now it’s time for Numeric conversions, which are similar to string conversions in that we utilize the Number() method to explicitly convert strings, booleans, and other numeric expressions to a number.
Implicit numeric conversion is challenging since it occurs in a variety of situations:
- Comparison operators (>, <, =>, <=)
- arithmetic operators ( `+` / % ).
- Bitwise operators ( | & ^ ~)
- unary + operator
- loose equality operator == (incl. !=).
// Explicit conversion into a number
Number(" 12 "); // 12
Number("-12.34"); // -12.34
Number("\n"); // 0
//null and undefined into a number
Number(null); // 0
Number(undefined); // NaN
// Booleans into Number
Number(true); // 1
Number(false); // 0
// Difference between results of the same prompt..
prompt('what is you age?'); // '26'
Number(prompt('what is you age?')); // 26
Code language: JavaScript (javascript)
Converting Boolean Values
Boolean conversion is the process of converting an expression to a boolean value. The Boolean() Function can do this translation either directly or implicitly in logical contexts (such as if/else) or when the logical operators (||, &&,! ) are used.
Consider the following example:
Boolean(2); // true
// conversion to boolean implicitly in an statement
if(' ') {console.log(`Empty string`)}; // Empty string
// implicit conversions due to logical operators
!! 2; // true
'' || 23; // 23
Code language: JavaScript (javascript)
Converting Symbols
Converting symbols is a bit complicated because it can only be done directly, not implicitly. Symbols, in particular, cannot be coerced into strings or numbers, preventing them from being unintentionally utilized as properties that would otherwise behave like a symbol.
When we use console.log() to display the outputs of the symbols, it works because console.log() creates useful results by calling String() on the symbols.
Consider the following example:
let mySymbol = Symbol.for("mySymbol"),
str = String(mySymbol);
console.log(str); // 'Symbol(mySymbol)'
Code language: JavaScript (javascript)
Conclusion
This was about type conversion in JS. If you have any query related to React or JavaScript, do drop it down in the comment section also do check out codedamn courses if you want to learn more about JavaScript and React with its use cases and amazing projects. They also have an in-built playground for different programming languages and environment sets so do check that out and join codedamn’s community!
Sharing is caring
Did you like what mansi wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: