Type Coercion refers to the process of automatic or implicit conversion of values from one data to another. This includes conversion from Number To String, String To Number, Boolean To Number etc.
1. String to Number Conversion
let x = 10 + '10';
console.log(x);
/* Output: 1010 *first value is Number and other string.
the number 10 is implicitly converted into string '10'. */
// ex. 01
let y = '20' + 10;
console.log(y);
// Output : 2010
// ex. 02
let z = true + '10';
console.log(z);
// Output: true10
// examples
let a = '10' - 10 //Output : 0;
let b = 10 - '10' //Output: 0 ;
// ex. 03 Using Operators
/* Note: Using Operators values that are not Number are converted into Number data type */
let c = 10 - '5'; // Output: 5;
let d = 10 * '5'; // Output: 50;
let e = 10 / '5'; // Output: 2;
let f = 10 % '5'; // Output: 0;
// ex. 03 Boolean to Number
/* Note: Boolean value is converted into number i.e. boolean value + number value.
Boolean value is 0 for false and 1 for true
*/
let g = true + 2;
console.log(g); // Output: 3;
let h = false + 2;
// Output: 2;let myVar; myVar = 52; console.log(myVar); // Output: 52; // convert to string myVar = String(52); console.log(myVar, (typeof myVar)); // Output: 52 type is string // Boolean to srting let a = String(true); // Output: true type of string; // Date to string let date = String(new Date()); // Output: date in string; // Array into String let array = String[1, 2, 3, 4] // Output: 1,2,3,4 in string let i = 40; console.log(i.toString()); // // Number let stri = Number('123456'); // Output: 123456 type of Number let a = Number(true); // Output: 1 type of number; let b = Number(false)l // Output: 0 type of number; let c = Number(35.0658) // Output: 35.0658; let d = parsefloat('35.068')// Output: 35.068 type of number let e = parsefloat('35.068'); console.log(e.toFixed(), (typeof e)); // Output:35 number console.log(e.toFixed(2), (typeof e)); // Output:35.06 number

Comments
Post a Comment