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

11.1. Data Type Conversion

We've seen that JavaScript is an untyped language (or, perhaps more accurately, a loosely typed or dynamically typed language). This means, for example, that we don't have to specify the data type of a variable when we declare it. Being untyped gives JavaScript the flexibility and simplicity that are desirable for a scripting language (although those features come at the expense of rigor, which is important for the longer, more complex programs often written in stricter languages such as C and Java). An important feature of JavaScript's flexible treatment of data types is the automatic type conversions it performs. For example, if you pass a number to the document.write( ) method, JavaScript automatically converts that value into its equivalent string representation. Similarly, if you test a string value in the condition of an if statement, JavaScript automatically converts that string to a boolean value -- to false if the string is empty and to true otherwise.

The basic rule is that when a value of one type is used in a context that requires a value of some other type, JavaScript automatically attempts to convert the value as needed. So, for example, if a number is used in a boolean context, it is converted to a boolean. If an object is used in a string context, it is converted to a string. If a string is used in a numeric context, JavaScript attempts to convert it to a number. Table 11-1 summarizes each of these conversions -- it shows the conversion that is performed when a particular type of value is used in a particular context. The sections that follow the table provide more detail about type conversions in JavaScript.


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


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