JavaScript Type Conversion

July 18, 2018
js data types conversion primitives objects

JavaScript is a loosely typed language. Although due to type coercion, JavaScript will automatically convert many values, it is often best practice to manually convert values between types in order to achieve expected results.

This tutorial will guide you through converting JavaScript’s primitive data types (both implicitly and explicitly).

Converting to Number

  1. Number() – explicit

    // Number:remains the same number
    Number(324) // 324
    // String:will be converted to number if it's variable
    Number('324') // 324
    // String:will return NaN if it is of non-number
    Number('324abc') // NaN
    // Empty string: returns 0
    Number('') // 0
    // Boolean:true --> 1,false --> 0
    Number(true) // 1
    Number(false) // 0
    // undefined:will be converted to NaN
    Number(undefined) // NaN
    // null:returns 0
    Number(null) // 0
  2. parseInt() – explicit

    The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). Syntax: parseInt(string, radix);

    If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.

    parseInt("10.33", 10)  // 10
    parseInt("10 20 30")   // 10
    parseInt("10 years")   // 10
    parseInt("years 10")   // NaN
    parseInt("1.23e4")     // 1
  3. parseFloat() – explicit

    The parseFloat() function parses an argument and returns a floating point number.

    parseFloat('0.0314E+2')  // 3.14
    parseFloat('\t\v\r12.34\n ') // 12.34
    parseFloat('FF2') // NaN
  4. x - 0 – implicit

    As a programming language, JavaScript is very tolerant of unexpected values. Because of this, JavaScript will attempt to convert unexpected values rather than reject them outright. This implicit conversion is known as type coercion.

    When using strings that can be evaluated to numbers with mathematical operators, you’ll find that JavaScript is able to handle the values by implicitly converting the strings to numbers:

    "15" - "10"  // 5
    "18" % "5"   // 3
    // When working with strings, + stands for concatenation
    "2" + "3"    // "23"

    Not like the ambiguity that + operator may cause, we can still use the - operator to conveniently convert any variable string to number like this:

    '123' - 0  // 123
    '123' + 0  // "1230", unexpected result
  5. +x or -x – implicit

    The Unary Plus + operator can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

    The Unary Negation - operator can convert the operand into a number and negate after.

    These two operators are super powerful yet simple when converting things to numbers. Highly recommend!

    +'-3'      // -3
    +'123e-5'  // 0.00123
    -'3.14'    // -3.14
    -false     // -0
    +'meow'    // NaN

Converting to Boolean

  1. Boolean() – explicit

    This can be useful for determining whether a user entered data into a text field or not, for example. The parameter that passed into the argument will be translated into a Boolean context, so remember the differences between the truthy and falsy values (See my previous post)

    Boolean(undefined) // false
    Boolean("text")    // true
    Boolean("")        // false
  2. !!x – implicit

    Use the double NOT operator !! for boolean type casting:

    !!'text'   //true

Converting to String

  1. x.toString() or String() – explicit

    By using String(x) or x.toString() we are able to explicitly convert values of Boolean or number data types to string values in order to ensure that our code behaves as we anticipate.

    Null and undefined data types do not have toString() method, but they can still use String() function.

    3.14e2.toString()  // "314"
    String(1==2)       // "false"
    String(null)       // "null"
    String(undefined)  // "undefined"

    Every object has toString() and String() methods that are automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. The return values are the same: [object Object]

  2. x+'' – implicit

    1+""           // '1'
    True+""        // 'true'
    Null+""        // 'null'
    Undefined+''   // "undefined"

Primitives vs Objects

Now that we’ve got primitives and objects, what’s the idea behind all of that?

It’s related to memory management.

Behind the scenes, JS of course has to store the values you assign to properties or variable in memory. And JS knows two types of memory: The Stack and the Heap.

The stack is essentially an easy-to-access memory that simply manages its items as a stack. Only items for which the size is known in advance can go onto the stack. This is the case for numbers, strings, booleans.

The heap is a memory for items of which you can’t pre-determine the exact size and structure. Since objects and arrays can be mutated and change at runtime, they have to go into the heap therefore. For each heap item, the exact address is stored in a pointer which points at the item in the heap. This pointer with ADDRESS in turn is stored on the stack.

Read more in this Medium article about memory allocation and garbage collection.

comments powered by Disqus