JavaScript #10 ~ Type Conversion and Coercion

HJ's Coding Journey·2021년 6월 6일
0

[Learn] JavaScript

목록 보기
11/20

When we try to write code for a program, we often need to deal with changing the code from one type to another such as a 'string to a number' or a 'number to a boolean'. During this process, the data types are converted by either type conversion or type coercion.

Type Conversion

Type conversion is when the type of code is explicitly converted by developers. When writig code using operators (ex. +, -), JavaScript will always concatenate everything based on the logical type of the code. Which is why we may end up with an unexpected type of result. As such, we need to use function methods that changes the type of code.

// Type conversion methods
Number();
String();
Boolean();

Applying the type conversion method will change the code to its designated type.

// Ex) Converting a number to a string
const inputYear = '1991';
console.log(Number(inputYear)); // 1991
console.log(inputYear + 18); // 2009 instead of '199118';

Type Coercion

Type coercion is when JavaScript automatically converts the type of a code behind the scenes. In fact, most of the time, developers rely mostly on type coercion to concatenate code rather than manually trying to use type conversion. This is said to be an advantage of using JavaScript. If JavaScript did not have this functionality, developers would have to manually use the type conversion method for every single code that is written 😱.

// type coercion (authomatically converts number to string)
console.log('I am ' + 23 + ' years old'); // 'I am 23 years old'

What about the rest of the operators (-, *, /, >, <)? All the other operators would be calculated as other data types instead of a string. Only the + operator will result as a string type.

console.log('23' - '10' - 3); // 10
console.log('23' * 2); // 11.5
console.log('23' > '18'); // true

Truthy and Falsy Values

How would type coercion function with boolean values? In order to answer this question we would first need to understand truthy and falsy values. There are 6 types of falsy values:

false
0
''
undefined
null
NaN

All the other values besides the ones listed above are considered truthy values.

JavaScript's type coercion functionality uses truthy and falsy values within boolean context to make logical decisions within logical operators or if/else statements. As such, results will differ depending on whether the value is truthy or falsy.

// Ex) How much money did I get? (Truthy Value)
const money = 1000;
if (money) {
  console.log('I just got money! :)'); // 1st condition is executed
} else {
  console.log('You should get a job!');
}
// Ex) How much money did I get? (Falsy Value)
const money = 0;
if (money) {
  console.log('I just got money! :)');
} else {
  console.log('You should get a job!'); // 2nd condition is executed
}
profile
Improving Everyday

0개의 댓글