#8 Type Conversion & Coercion in JavaScript

Telusko
19 May 202112:53

Summary

TLDRIn this JavaScript tutorial by Davin Rady, the concept of type conversion and type coercion is explored. The video explains how data types like numbers, strings, and booleans can be explicitly converted using language-specific functions. It also delves into implicit type coercion, where JavaScript automatically changes data types during operations, leading to potential bugs if not carefully managed. The tutorial covers practical examples, such as converting numbers to strings for storing zip codes and telephone numbers, and discusses the importance of being vigilant with these operations to avoid unexpected results.

Takeaways

  • 😀 The video discusses type conversion and type coercion in JavaScript, explaining the difference between the two concepts.
  • 🔢 Data types in JavaScript include numbers, strings, booleans, and the need to convert data between these types for various operations.
  • 💡 Type conversion is explicit, where developers use specific functions like `String()` or `Number()` to change data types.
  • 📝 Type coercion is implicit, where JavaScript automatically changes data types to perform operations, such as when adding a number and a string.
  • 👀 The `typeof` operator is used to check the data type of a variable in JavaScript.
  • 📌 Storing data like zip codes or phone numbers as strings is recommended when no calculations are needed.
  • 🔄 The plus (`+`) operator can perform both addition and string concatenation, depending on the types of operands involved.
  • 🤔 JavaScript's type coercion can sometimes lead to unexpected results and bugs if not handled carefully.
  • 👍 JavaScript is appreciated for its flexibility in understanding the developer's intent and performing type coercion to meet that intent.
  • 🚫 However, JavaScript's automatic type coercion can also be frustrating when it overrides the developer's intended operations.
  • 🔍 The video suggests using functions like `parseInt()` to convert strings to integers, especially when the string contains non-numeric characters at the start.

Q & A

  • What is the main topic of the video?

    -The main topic of the video is JavaScript type conversion and type coercion.

  • Why is type conversion necessary in programming?

    -Type conversion is necessary when you want to change the data format, for example, converting a number to a string or vice versa, to meet specific requirements such as storing a zip code as a string.

  • What is the purpose of the 'typeof' operator in JavaScript?

    -The 'typeof' operator is used to print the type of data of a variable in JavaScript.

  • How can you convert a number to a string in JavaScript?

    -You can convert a number to a string in JavaScript by using the String function and passing the number as an argument, like String(num).

  • What happens when you try to perform an operation with a number and a string using the plus (+) operator?

    -When using the plus (+) operator with a number and a string, JavaScript performs type coercion and treats the operation as string concatenation, converting the number to a string.

  • How does JavaScript handle type coercion with the subtraction operator?

    -With the subtraction operator, JavaScript converts the string to a number if possible, allowing the operation to proceed as a numerical subtraction.

  • What is the result of converting a non-zero number to a boolean in JavaScript?

    -In JavaScript, converting a non-zero number to a boolean results in true, as all non-zero numbers are considered truthy values.

  • What is the result of converting zero to a boolean in JavaScript?

    -In JavaScript, converting zero to a boolean results in false, as zero is considered a falsy value.

  • How can you convert a string that represents a number into an actual number in JavaScript?

    -You can use the parseInt function to convert a string that represents a number into an actual number in JavaScript.

  • What does the unary plus (+) operator do when used with a string in JavaScript?

    -The unary plus (+) operator attempts to convert the string into a number in JavaScript.

  • What are some of the falsy values in JavaScript?

    -In JavaScript, falsy values include 0, null, undefined, NaN, '', and false.

  • What is the difference between type conversion and type coercion in JavaScript?

    -Type conversion is the explicit action of a developer to convert data from one type to another using functions like String(), Number(), or Boolean(). Type coercion is an implicit action performed by JavaScript where the engine changes the type of data during an operation to make it compatible, such as when adding a number and a string.

Outlines

00:00

🔢 JavaScript Type Conversion Basics

In this paragraph, Davin Rady introduces the concept of type conversion and coercion in JavaScript. He explains the necessity of converting data types like numbers, strings, and booleans for various programming requirements. Davin demonstrates how to explicitly convert a number to a string using the String() function and vice versa with the Number() function. He also touches on the topic of converting numbers to boolean values, setting the stage for a deeper dive into type coercion and its implications in subsequent paragraphs.

05:01

🤔 Understanding Type Coercion in JavaScript

This paragraph delves into the automatic process of type coercion in JavaScript. Davin Rady illustrates how JavaScript handles operations between different data types, such as adding a number and a string, which results in the number being coerced into a string to perform concatenation. He further explains that subtraction between a string and a number will coerce the string into a number. Davin also discusses the behavior of boolean values with the NOT operator and how different values are treated as truthy or falsy in JavaScript, with zero and null being the only falsy values, while all others are truthy.

10:03

🛠️ Advanced JavaScript Type Conversion Techniques

The final paragraph focuses on advanced type conversion techniques in JavaScript. Davin Rady discusses the use of unary plus to convert a string to a number and the potential issues that can arise from JavaScript's type coercion, such as unexpected NaN (Not a Number) results. He introduces the parseInt function as a method to extract integer values from strings, highlighting its limitations when encountering non-numeric characters. Davin emphasizes the importance of being cautious with type operations to avoid bugs and encourages viewers to explore various type conversion functions available in JavaScript.

Mindmap

Keywords

💡Type Conversion

Type conversion in the context of the video refers to the explicit process of changing a variable's data type from one format to another, such as converting a number to a string or vice versa. It is a fundamental concept in JavaScript that allows developers to manipulate data according to their needs. For instance, the script mentions using the 'String' function to convert a numerical value to a string format, which is crucial when storing non-calculative data like zip codes.

💡Type Coercion

Type coercion is an implicit process in JavaScript where the language automatically converts one data type to another during operations. This is often seen in expressions that involve different data types. The video illustrates this with the plus '+' operator, which can perform concatenation when a string and a number are involved, thus converting the number to a string.

💡Data Types

Data types are categories for data that determine what kind of values they can represent, such as numbers, strings, and booleans. The video discusses the necessity of understanding and converting between these types, as it affects how data is manipulated and displayed in JavaScript. For example, the script explains that numbers are suitable for calculations, while strings are better for non-numeric data like telephone numbers.

💡Boolean

A boolean is a data type in JavaScript that can only take two values: true or false. The video explains how boolean values can be derived from other data types through type coercion, such as when a number is converted to a boolean, where all numbers except zero evaluate to true, and zero evaluates to false.

💡Unary Operators

Unary operators in the video are used to perform operations on a single operand. An example given is the plus '+' operator used for converting a string to a number, which is a unary operation that attempts to parse the string into a numerical value.

💡Concatenation

Concatenation is the process of joining two strings together. The video demonstrates this with the plus '+' operator, which, when used with a string and a number, coerces the number into a string and concatenates them.

💡Truthy and Falsy Values

In JavaScript, truthy and falsy values refer to the values that are treated as true or false in boolean contexts. The video explains that zero, null, undefined, NaN, and the empty string are considered falsy, while all other values are truthy. This concept is crucial for understanding how boolean logic works in JavaScript.

💡NaN

NaN stands for 'Not a Number' and is a special value in JavaScript used to represent a value that is not a legal number. The video mentions NaN in the context of attempting to convert a string that cannot be parsed into a number, such as 'navin', resulting in NaN.

💡parseInt

parseInt is a function in JavaScript that parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). The video uses parseInt to convert a string containing numbers into an integer, highlighting its utility when extracting numerical values from strings.

💡Variable Assignment

Variable assignment in the video is demonstrated through the use of the '=' operator, which assigns a value to a variable. The script discusses how changing the value of a variable can change its data type, illustrating the dynamic nature of JavaScript variables.

💡JavaScript

JavaScript, the main theme of the video, is a programming language that is primarily used for client-side web development. The video discusses specific features of JavaScript, such as type conversion and coercion, to demonstrate how data is manipulated within this language.

Highlights

Introduction to type conversion and type coercion in JavaScript.

Explanation of why type conversion is necessary, such as converting data from number to string or vice versa.

Demonstration of using the 'typeof' operator to print the data type of a variable.

How to convert a number to a string format using the String() function.

Example of converting a string to a number using the Number() function.

Discussion on the concept of type conversion as explicit conversion by the developer.

Introduction to type coercion as implicit conversion performed by JavaScript.

Illustration of how JavaScript handles the plus operator with different data types, leading to type coercion.

Explanation of how JavaScript converts types based on the operator used, such as converting a string to a number with the subtraction operator.

The impact of using the 'not' operator on boolean values and how it affects type conversion.

Understanding truthy and falsy values in JavaScript, with examples including numbers and null.

The unique behavior of zero as a falsy value when converting numbers to boolean.

How JavaScript handles type coercion with the unary plus operator to convert strings to numbers.

The use of parseInt function to convert strings that represent integers into actual numbers.

The importance of being cautious with type coercion to avoid unexpected bugs in JavaScript.

Encouragement for viewers to explore different type conversion functions and understand their applications.

Conclusion and invitation for feedback on the video content.

Transcripts

play00:05

[Music]

play00:05

welcome back aliens my name is davin rady and  let's continue with this series on javascript  

play00:10

now in this video we'll talk about type conversion  and type coercion now why do we have two different  

play00:15

words let's understand that now first of all  it doesn't matter which language you work with  

play00:20

you have something in common right you actually  work with data but sometimes you want to convert  

play00:26

your data in specific format example we have  talked about data types right we have numbers  

play00:30

string boolean and there might be an option  or there might be a requirement where you have  

play00:35

to convert your data from number to string or  from string to number or from number to boolean  

play00:40

how do we do that now let's say let me create  a variable here so i will say num this time i'm  

play00:45

using a dark theme basically a high contrast so  let me know your feedback in the comments section  

play00:50

uh so finally we are on the dark theme yeah let  me create a number here right so this is a number  

play00:55

now we have seen how do you print the type of data  of course when you want to print the data as it  

play01:00

is we can simply print num right now this will  print data example if i run this code you got 6  

play01:05

but what if you want to print a type of  it in that case you can use a very special  

play01:10

operator which we have seen earlier which is  type off and you can print the type of num  

play01:15

so basically we are printing two things here we  are printing num and we are printing type of num  

play01:19

and let's see what happens and you can see we  got six and we got number that means the type  

play01:24

of this num is number that is working right but  what if i want to store this num in a different  

play01:30

format i want this to be in string format can we  do this now you will think hey why do we do that  

play01:36

so example let's say if you want to store a  pin called a zip code of area which is the best  

play01:41

format should you store the zip code in number  or in a string format see whenever you don't  

play01:46

want to perform any operation it's better to store  that in a string format example telephone number  

play01:51

zip code or whatever big number you have when  you want to perform calculation that's why  

play01:55

number makes sense right so here i want to store  this six in a string format in that case you have  

play02:01

to convert that right you have to perform  some operation so we have a specific thing  

play02:06

called a string so we'll pass string here  when you pass this number 6 inside a string  

play02:12

it will give you a string format so this  number is getting stored in a string format now  

play02:17

will it work let's try so let me just run this  code once again and you can see we got six  

play02:21

no change in data of course you have not got s i  x what you got is number six and you got a string  

play02:28

okay so this is working right and you can also do  reverse if you have a number in a string format  

play02:33

let's say one two three so now if you run this  code of course the data is in string format 123  

play02:37

is in string format and if you want to perform  operation you have to convert that into number  

play02:42

in order to do that we can simply say number  and you can give a bracket and this will work  

play02:48

right so if you run this code you got number the  same thing again you can do with boolean okay so  

play02:52

you can convert a number up with boolean but  that's a different thing we'll do that later  

play02:56

the interesting thing is this is type conversion  right you are able to convert a number  

play03:00

in different format this is explicit conversion  because basically you as a developer you are  

play03:05

trying to convert a data from one format to the  format it's working right but then javascript  

play03:13

went ahead javascript says hey you have type  conversions that's great let me give you something  

play03:18

called type conversion now what it means so let's  say i have a number here i'll say num or maybe  

play03:23

i will not go for any specific name because  num represents a name right so i will go with  

play03:28

let's say x i know it's not a good variable name  but just for the example here we can go with it  

play03:33

so let's say i have a variable x and i want  to print x here and i want to print the type  

play03:37

of it of course we are printing the data we are  printing the type of this data and the output  

play03:41

you are getting is undefined undefined of course  that makes sense right now what i will do here is  

play03:47

i will assign data to it so when you assign the  data it will change the type of it now what did i  

play03:51

want to assign let me just do that here so i will  say x is equal to six or maybe a different number  

play03:57

this time so let's go for x equal to eight now if  we do the same thing i just want to copy and paste  

play04:02

actually where i'm just reusing the code right  so after changing the value of x now let's try so  

play04:07

you can see we got undefined undefined because  that was the first time and then we got eight  

play04:11

number because this is the number if i change  the same thing again let's say i want to perform  

play04:16

some operation so i can simply say x is equal to i  want to add x with a string what do you think what  

play04:22

would happen and what type of string i want to  add maybe i just want to add empty string i don't  

play04:27

even have some specific type of string here right  it's it's an empty string now what will happen of  

play04:33

course i should also print the console here okay  now let me try and you can see this time we got  

play04:38

string so basically whenever you have a number and  you are you have a string this plus operator here  

play04:44

it got confused the idea behind a plus operator is  to add two numbers right but this time we have a  

play04:49

number and a string confusion right so coercion  comes into picture so javascript says okay in  

play04:55

this case every time you have two different data  and you want to perform some operation you have  

play05:01

to come to some consensus right either both has to  be same type it either it should be both string or  

play05:06

both number so in this case it goes for the string  because we have string at one end now whenever you  

play05:11

have string and when you use plus operator it is  actually concatenation so basically we are joining  

play05:16

two strings for example let's say you have naveen  you have ready two different strings you use a  

play05:21

plus orbital basically you are concatenating it in  this case as well even if you have x which is the  

play05:27

number and you have a string it will convert that  into string but not always not always when you use  

play05:32

a string a number it will give the same results  example let's say at this point if you see this is  

play05:37

a type of string right this x is a type of string  what if i do x equal to x minus 2. now you tell me  

play05:43

what will happen of course i have to print it as  well so pause this video and let me know what will  

play05:48

happen because x is a string now 2 is a number so  how it should behave should we get 8 minus 2 6 or  

play05:56

should we get some weird answer or maybe it should  be nand right which is because you are subtracting  

play06:00

a number from a string and that is weird so let's  let's see what happens so if you run this code  

play06:05

i hope you have answered that in the comment  section you got number so this is what happens  

play06:09

when you have a subtraction operator with a string  it will convert that into number so this is type  

play06:15

coercion so based on what type of operator you're  using based on what's the requirement javascript  

play06:20

engine will change that for you in fact we can  also do with boolean so we know right boolean is  

play06:25

true or false now the way you can manipulate  boolean is with the help of some operators  

play06:30

one of them is exclamation exclamation will simply  replace or it will do the opposite so if it is  

play06:36

true it will give you false if it is false it will  give you true right so exclamation actually means  

play06:41

not so there's a not operator with boolean which  will change the type so from true to false false  

play06:46

true now let me just do that so i will say x equal  to not x so even if it is a number format so you  

play06:51

can see x in this case is number right so you  are applying a not operator or number because  

play06:56

the naught will only work with boolean right and  you are giving a number so in this case it will  

play07:01

convert that into boolean and then it will perform  the not operation and let's see what happens but  

play07:06

the question is will you get true or false so  even if i say it converts this from number to  

play07:12

boolean what happens is it true or false let's try  let's run this code oh i'm not printing it my bad  

play07:18

let me print this and you can see we got false  boolean so boolean makes sense but why false  

play07:23

that means you are performing an operation the  output of that operation is false that means  

play07:27

initially the value of x was true that means  if you try to convert a number into boolean  

play07:34

if that number is 6 it will give you true only  6 it's actually any number example let me just  

play07:42

do that so what i will do is i will just go  to console and console.log and let me convert  

play07:48

a number let's say i have a number seven and  i want to convert this into boolean how do we  

play07:52

convert a number into boolean the same way we did  it for the number and string with the help of that  

play07:57

keyword number string here let me use boolean  so i'm passing 7 to a boolean right so it will  

play08:02

convert this 7 into a boolean format but what you  will get you will you get true or false let's try  

play08:09

so when i run this code you can see we got true  okay so for six it just giving you true for seven  

play08:14

is giving you true i thought it will be even odd  so even numbers will get true or number will get  

play08:18

false but that's not the case every number  is giving you true let me try negative number  

play08:22

so if i say minus seven let's see it's  still true okay now after trying out all  

play08:27

the different combinations let's try zero and  the moment you try zero and if you underscore  

play08:31

you can see we got false that means all  the numbers are true only zero is false  

play08:37

why is because the actual implementation of  boolean happens in that way 0 is false 1 is  

play08:42

true right if it is not 0 everything is true but  you can actually calculate with each number so  

play08:48

they simply go with simple formula if it is 0 it's  false if it is all the other numbers it is true  

play08:53

and this is called uh truthy and the falsie values  i know that that's tricky it's not just with  

play08:58

numbers it's also with other types example let me  convert into boolean of type null now what will  

play09:03

happen if we try to convert null into boolean and  if you're on this code you can see we got false so  

play09:08

even null is a false value so whenever you try to  convert something into boolean and if that gives  

play09:15

you false it is false value if you pass something  and if you're trying to convert that into boolean  

play09:20

if it is giving you true that's called a truthy  value example after some time will start working  

play09:24

with functions objects whatever your data you pass  so if you try to convert object into boolean it  

play09:30

will give you true if you try to pass a function  to and convert into boolean it will give you true  

play09:34

cool what about undefined let me just try that  so we'll try it with undefined also it will give  

play09:39

you false so these are all false values okay  apart from this everything is truthy value so  

play09:44

you can see the list if you have something like  this and if you try to convert these things into  

play09:49

boolean you will get false and all the other  thing will give you true uh let me just try  

play09:53

with stringer we have not tried with string yet so  what i will do is i'll pass the string like naveen  

play09:58

now what happens nobody is true or false of course  nothing is true let's try and you can see we got  

play10:03

true now since it's not a part of the false values  it's true so just reiterate whenever you have a  

play10:08

number and a string it will convert that into  string when you apply the addition operator but  

play10:12

when you perform this subtraction operator it will  convergent number so javascript is smart enough to  

play10:17

know what should be done and that's one thing i  love and hate about javascript we love this thing  

play10:23

because it helps you it actually understands what  you need and it will give the output the reason i  

play10:28

also hate it is because it tries to convert things  the way it wants sometimes you don't intend to do  

play10:34

that and you want others but javascript says  okay you're doing this i will allow you and i  

play10:38

will help you here we don't want your help we want  others because this will eventually lead to bugs  

play10:44

okay and that's why you have to very alert when  you're doing these operations in fact we have  

play10:49

some more ways example let's say i want to do plus  operator here right so we have x in string format  

play10:53

here and you want to okay let me just remove  this part just to make it simple yeah so we have  

play10:58

x which is string format right so if you run this  code so you can see we got 82 because you have  

play11:03

eight here which is x and then you got two so you  got 82. but in this case i want to convert this  

play11:08

into a number in that case you can use unary  operators of course we'll talk about orbitals  

play11:13

later in detail but so whenever you add a plus  here it tries to convert this string into number  

play11:18

let's try that and you can see we got numbers so  we got 10 which is the addition of eight and two  

play11:22

and you've got a number okay there are more ways  actually to convert the string into integer or  

play11:27

the other format so let me just try that so let's  say we have x and the value of x is one two three  

play11:33

navin okay now in this case i want to convert  this into a number format but of course you can't  

play11:38

convert that into number format right because we  have naveen there so if you try to do that with  

play11:42

the help of a number function so let's say if i  do let me just print that first as it is let's  

play11:46

see what happens if you print this and you can see  we got one two three naveen okay that works but  

play11:51

if you try to convert that into number because we  did that before let's see what happens so if we  

play11:57

try to do that and if you run this code you can  see we got nan which is not number we don't want  

play12:01

this what we want is it should be able to convert  that and at least fetch these first integer values  

play12:06

so in this case you can actually use parseint  so pass int is a special function which will  

play12:11

accept a string it will try to convert that number  okay it will do its hard work to convert a string  

play12:17

into number and you can see we got 123 but what  happens if you have a character at the start in  

play12:22

this case it will not work so i have to make sure  that you have numbers at the start so it will try  

play12:26

to convert that into numbers right so that's how  you can do it uh so try out different functions  

play12:31

you can go to google and search for different type  conversions functions and you will get those so i  

play12:35

hope you enjoyed this video let me in the comments  section and do some stuff for the videos bye you

Rate This

5.0 / 5 (0 votes)

Related Tags
JavaScriptType ConversionType CoercionData TypesString ConversionNumber ConversionBoolean ConversionOperator BehaviorProgramming TutorialDeveloper TipsCode Examples