Working with Variables and Data Types in JavaScript

  • 6/15/2013

Learning about type conversions

Before finishing the discussion on data types and variables, you should know a bit about type conversions, or converting between data types. JavaScript usually performs implicit type conversion for you, but in many cases, you can explicitly cast, or convert, a variable from one type to another.

Number conversions

You’ve already seen a conversion between two number formats, hexadecimal to base 10, in the example discussed in the section Data types in JavaScript earlier in this chapter. However, you can convert numbers to strings as well. JavaScript implicitly converts a number to a string when the number is used in a string context.

To explicitly convert a number to a string, cast the number as a string, as in this example:

// Convert myNumString as a string with value of 100
var myNumString = String(100);

String conversions

In the same way that you can convert numbers to strings, you can convert strings to numbers. You do this by casting the string as a number.

var myNumString = "100";
var myNum = Number(myNumString);

Boolean conversions

Booleans are converted to numbers automatically when used in a numeric context. The value of true becomes 1, and the value of false becomes 0. When used in a string context, true becomes “true”, and false becomes “false”. The Boolean() function exists if you need to explicitly convert a number or string to a Boolean value.