Javascript

A collection of tricky JavaScript expressions with Automatic Type Conversion

Sometimes JavaScript program outputs is not what a developer might expect. In this minipost we have gathered a small collection of expressions that are evaluated with not such an expected outcome. The below expressions can become very tricky and could be appeared as interview questions.

Automatic Type Conversion

When a JavaScript operator is applied to the “wrong” type of value, it is quietly converted to a type using a set of rules that are often, not what is expected. This is called type coercion.

Let's demonstrate the following tricky expressions and their outputs:

> 4 * null;
< 0

In this expression null becomes 0 and the output is also 0.

> "4" - 1;
< 3

The String "4" is being evaluated as integer 4 and the arithmetic operation of subtraction is being performed resulting to the arithmetic 3.

> "4" + 1;
< "41"

In this expression the String concatenation is being evaluated before the numeric addition. Therefore, the 1 is converted to "1" and the output is the concatenated String of "41".

> "four" * 1;
< NaN
> undefined * 1;
< NaN
> NaN * 1;
< NaN

When we cannot have a straightforward conversion to a number, the value NaN is produced. Further on, NaN in an expression keeps producing NaN outputs.

Buy Me A Coffee

Read also the following