Type Conversions

Type Conversions

JavaScript is a pretty flexible language when it comes to handling different types of values. It tries to help you out by automatically converting values to the type it expects, even if you give it something else. For example, when JavaScript is expecting a boolean (true or false), you can actually give it any type of value, and it will convert it for you. Some values are considered “truthy” (meaning they convert to true), while others are “falsy” (meaning they convert to false).

If JavaScript wants a string, it'll turn whatever value you give it into a string. Need a number? No problem—JavaScript will do its best to convert the value into a number too. Let’s take a look at a few examples to see how this works:

Boolean Conversion:

if ("Hello") {
  // "Hello" is a truthy value
  console.log("This is true!");
}

if (0) {
  // 0 is a falsy value
  console.log("This won't print.");
}

String Conversion:

let num = 42;
console.log("The answer is " + num); // Converts 42 to "42" and concatenates

Number Conversion:

let str = "123";
let result = Number(str); // Converts "123" to 123
console.log(result + 1); // Outputs 124

When it comes to converting primitive values (like strings, numbers, and booleans), the rules are pretty straightforward. Converting to a string is well-defined for all primitive values—everything can be turned into a string. Converting to numbers is a bit trickier. If the string can be parsed as a number, it will convert. Spaces around the string are fine, but if there are any non-numeric characters, you’ll end up with NaN (Not-a-Number).

For example, " 123 " becomes 123, but "123abc" becomes NaN. And in boolean-to-number conversions, true turns into 1, while false and the empty string ("") convert to 0.

Finally, converting objects to primitives is more complex and not something we’ll get into on the blue belt series. That's a topic for a more advanced belt we can cover later.

=== vs ==

In JavaScript, you have two main operators to check if two values are equal, but they each have a slightly different way of doing it. The strict equality operator (===) is the more precise tool for comparing values. It checks both the value and the type, making sure they are the same. This means that 3 === '3' will be false because one is a number and the other is a string. This is usually the operator you want to use because it avoids the confusion that comes with JavaScript's flexible type conversions.

On the other hand, the loose equality operator (==) is a bit more lenient. It tries to be helpful (JavaScript does this a lot with types, it tries to be helpful) by converting values to a common type before making the comparison. This means that 3 == '3' will be true because JavaScript converts the string '3' to the number 3 before comparing them. However, this flexibility can sometimes lead to unexpected results, so it's good to be cautious when using ==.

Here’s an important point to remember: Just because JavaScript can convert one value to another doesn’t mean they are considered equal by the == operator. For instance, undefined is often treated as a falsy value in boolean contexts, so if (undefined) will evaluate as false. But undefined == false is false because undefined is never converted to false in the == comparison.

So, while == can be handy for some cases where type conversion is desired, it's generally safer to stick with === to avoid the quirks of JavaScript's type coercion and ensure your comparisons are clear and predictable.

Explicit Conversions

While the language often handles type conversions automatically, there are times when you might want to take control and perform these conversions explicitly. This can make your code clearer and help you avoid unexpected results.

To manually convert values, you can use a few handy functions: Boolean(), Number(), and String(). These functions make it easy to ensure that your values are of the type you need. For example, if you have a string that represents a number and you want to use it as a number, you can use Number():

let str = "123";
let num = Number(str); // num is now the number 123

Similarly, if you want to convert a number to a string, you can use String():

let num = 456;
let str = String(num); // str is now the string "456"

For more specific needs, especially when dealing with financial or scientific data, you might want to format numbers in a particular way. JavaScript provides three methods for converting numbers to strings with precision:

  • toFixed(digits): Converts a number to a string, rounding to a specified number of decimal places. This is useful when you need a fixed number of decimal places for currency values. For example:
let price = 19.995;
console.log(price.toFixed(2)); // Output: "20.00"
  • toExponential(digits): Converts a number to a string using exponential notation, with one digit before the decimal point and a specified number of digits after the decimal point. This method is helpful for very large or small numbers:
let largeNumber = 123456;
console.log(largeNumber.toExponential(2)); // Output: "1.23e+5"
  • toPrecision(digits): Converts a number to a string with a specified number of significant digits. This method can switch to exponential notation if needed:
let num = 123.456789;
console.log(num.toPrecision(5)); // Output: "123.46"

All three methods will either round the number or pad with zeros to fit the required format. Using these methods helps you present numbers in a way that suits your application’s needs, making your data clearer and more accurate.

Study Style Notes

JavaScript's Flexibility with Types

  • Automatic Type Conversion: JavaScript automatically converts values to the expected type, even if the provided value is different.

Boolean Conversion

  • Conversion to Boolean: Values are converted to true or false based on their "truthiness" or "falsiness".
    • Truthy Values: Values that convert to true.
    • Falsy Values: Values that convert to false (e.g., 0, null, undefined, "").

String Conversion

  • Any Value to String: Any value can be converted to a string.
  • String Expectation: JavaScript will convert a value to a string when a string is expected.

Number Conversion

  • Conversion to Number: Values are converted to numbers if possible.
    • Non-numeric Strings: Result in NaN.
    • Spaces: Spaces around numeric strings are ignored, but non-numeric characters cause conversion to NaN.
    • Boolean to Number: true converts to 1, false converts to 0.

Primitive Value Conversions

  • To String: Any primitive can be converted to a string.
  • To Number: Converts to a number where possible, otherwise results in NaN.
  • To Boolean: Converts values based on their truthy or falsy evaluation.
  • Objects to Primitives: More complex conversions not covered at this level.

Equality Operators in JavaScript

  • Strict Equality (===):
    • Compares both the value and the type.
    • Does not perform type conversion; values must be of the same type to be considered equal.
    • Recommended for precise comparisons to avoid type coercion issues.
  • Loose Equality (==):
    • Converts values to a common type before comparing.
    • Allows comparisons between different types but may produce unexpected results.
    • undefined and null are equal to themselves but not to other falsy values.

Explicit Type Conversions

  • Why Use Explicit Conversions?
    • Provides control over the type of values.
    • Helps avoid unintended results from automatic type coercion.
  • Conversion Functions:
    • Boolean(value): Explicitly converts a value to a boolean.
    • Number(value): Explicitly converts a value to a number.
    • String(value): Explicitly converts a value to a string.

Number to String Methods

  • toFixed(digits): Converts a number to a string, rounding to a specified number of decimal places. Useful for formatting currency.
  • toExponential(digits): Converts a number to a string in exponential notation. Useful for very large or very small numbers.
  • toPrecision(digits): Converts a number to a string with a specified number of significant digits. Can switch to exponential notation if needed.

Purpose of These Methods

  • Control Over Formatting: These methods provide control over how numbers are formatted and displayed, which is useful for applications requiring specific numeric precision, such as financial or scientific data.