Changing types of data

To avoid unpredictable behaviour, you can force a variable n to be a number by using the assignment n *= 1 and to be a string by using the assignment n += "". Another option is to use the function typeof (discussed in the earlier section on types of data) to determine the type of a value and then make sure you deal with it appropriately.

We have already seen the function Boolean(); here we present it again with other functions that change types.

Function Type produced
Number() number
String() string
Boolean() Boolean

Note:

Hints:

  • undefined
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
2
console.log("Using Number");
console.log(Number(5));
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX