JavaScript Performs Automatic Data Type Conversion

JavaScript performs automatic type conversion when used in expressions and statements. For example, if you try to add a string value “Java” with a numeric value 4, then the numeric value 4 is converted to a string “4” and appends it to the string “Java”.

The result of the expression would be “Java 4”.

How type conversion is done?

Whenever an expression is evaluated the expression is parsed into its component unary and binary expressions based upon the order of preference of the operators. Then the component unary and binary expressions are evaluated. The expressions are evaluated according to the operators involved. If an operand takes a value of a type that is different from the type of the operand, then the operand is converted to a type that is valid for the operator.

Some of the conversions that take place when evaluating expressions are :

  1. Numeric values are converted to their equivalent string value.
  2. Boolean values are converted to 1 and 0 to support arithmetic operations.
  3. The null value is converted to 0 for arithmetic operations and false for logical operations.

The following example illustrates how type conversion of data types is done.

Code-

Conversion functions

Explicit type conversion can be done by JavaScript’s built-in functions such as parselnt(), parseFloat() and eval().

Parselnt():

This function is used to convert a string value into an integer, parselnt() returns the first integer contained in the string. For example :

parselnt(“5 script”) returns 5

parselnt(“JavaScript”) returns 0

parseFloat():

This function returns the first float value contained in a string or else returns 0. For example :

parseFloat(“5.4e4script”) returns 54000

parseFloat(“JavaScript”)   returns 0.

eval():

This function is used to convert a string expression to a numeric value. For example :

eval(“5+4”) returns 9

eval(“Java”) returns 0

The following example illustrates the use of the above three functions.

Code –