Type conversion in javascript:
JavaScript variables can be converted to a new variable and another data type either by the use of a JavaScript function
or automatically by JavaScript itself
javascript type conversions are possible only in the following combinations:
- number to string
2.string to number
- boolean conversions
the conversions to undefined or null type is not possible in javascript
example:
1.conversion of string to Number datatype in javascript
const inputYear = '1991';
console.log(Number(inputYear),inputYear);
console.log(Number(inputYear)+18);
2.conversion of string to number is not possible in the following caseas it would yield an reference error.
console.log(Number('Jonas'));
- Not an number(NaN is also a number type in javascript)
console.log(typeof NaN);
//conversion of integer to string
console.log(String(23),23);
type coersion in javascript
Type Coercion refers to the process of automatic or implicit conversion of values from one data type to another. This includes conversion from Number to String, String to Number, Boolean to Number etc. when different types of operators are applied to the values.
In case the behavior of the implicit conversion is not sure, the constructors of a data type can be used to convert any value to that datatype, like the Number(), String() or Boolean() constructor.
examples:
console.log(i am
+ 23 + years old
);
// the 23 is converted to the string type
console.log(23
+10
+2
);
//this will result in a string 23102
console.log(23
-3+12
);
//this will convert all the strings to Number datatype
let n=1
+1;
n=n-1;
console.log(n)
//the first thing is 11 as a string the n=n-1 will convert all of it to numbers and the result will be 10
Top comments (0)