• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 5. Operators > Number, String, or Boolean? Datatype Conversion

5.3. Number, String, or Boolean? Datatype Conversion

As defined earlier, JavaScript is a loosely typed language, which really means that you don't have to be concerned about what kind of data is stored in a variable. You can assign a number to x on one line and on the next line assign a string to x, you can compare numbers and strings, strings and Booleans, and so on. JavaScript automatically converts values when it assigns values to a variable or evaluates an expression. If data types are mixed (i.e., a number is compared with a string, a Boolean is compared with a number, a string is compared with a Boolean), JavaScript must decide how to handle the expression. Most of the time, letting JavaScript handle the data works fine, but there are times when you want to force a conversion of one type to another. For example, if you prompt a user for input, the input is set as a string. But, suppose you want to perform calculations on the incoming data, making it necessary to convert the strings to numbers. When using the + operator you want to add two numbers that have been entered as strings, not concatenate them, so you will then need to convert the data from string to number.

JavaScript provides three methods to convert the primitive data types. They are:


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint