JavaScript Type Conversions

JavaScript, like most programming languages, allows developers to convert values from one data type to another.

This process is known as type conversion.

In JavaScript, there are several different ways to convert a value from one type to another, including numeric, boolean, and string conversion.

String Conversion

String conversion in JavaScript is the process of converting a value to a string type. In JavaScript, string conversion can be performed using the built-in String() function. For example, the following code converts the boolean value false to a string:

1const bool = false;
2const str = String(bool); // "false"

Boolean Conversion

Boolean conversion in JavaScript is the process of converting a value to a boolean type. The boolean type has two possible values: true and false.

In JavaScript, boolean conversion can be performed using the built-in Boolean() function which follows two simple rules:

  1. Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false.
  2. Other values become true.

For example:

1const str = "hello";
2const bool = Boolean(str); // true
3const zero = 0;
4const zeroToBool = Boolean(zero) // false

Numeric Conversion

Numeric conversion in JavaScript is the process of converting a value from one numeric type to another. For example, a developer may want to convert an integer to a floating-point number, or vice versa. In JavaScript, this can be done using the built-in Number() function. For example, the following code converts the integer 2 to a floating-point number:

1const num = 2;
2const float = Number(num); // 2.0

In addition to converting between integer and floating-point numbers, the Number() function can also be used to convert other types of values to numbers. For example, it can be used to convert a string representation of a number to an actual number value.

1const str = "3.14";
2const num = Number(str); // 3.14

It's important to note that, in some cases, the Number() function may not be able to perform a numeric conversion. For example, if the input value is a non-numeric string or an array, the function will return the special value NaN (Not a Number).

1const str = "hello";
2const num = Number(str); // NaN

JavaScript is a trademark of Oracle Corporation in the US. All resources shared on Java5cript.com are owned by their respective creators.