Published on

Data Types (Part I)

9 mins

Authors
  • Name
    Juleshwar Babu
    Twitter

Table Of Contents


Source Link: https://javascript.info/data-types

Methods of primitives

  • Link: https://javascript.info/primitives-methods

  • The JS Engine implicitly converts the primitive into a relevant object with helper methods. This is for ease of use.

    let str = "hi"
    log(str.toUpperCase()) // HI
    
    /**
     * Behind the scenes line 2 looks like console.log((new String("hi")).toUpperCase())
    */
    

    Here’s what happens

    1. str is a primitive. To achieve this, a temp String object is created which has all these useful methods.
    2. The method runs and outputs the result.
    3. The temp object is destroyed.

    The object only exists during the running of that line and is promptly destroyed.

  • new Number/Boolean/String is an anti-pattern!

    // Anti-pattern
    let zero = new Number(0)
    console.log(typeof zero) // **object!
    
    //** Instead do this
    zero = Number("0")
    console.log(typeof zero) // number
    

    Instead you can just use the constructor without the new for type conversion

Numbers

  • Link: https://javascript.info/number

  • https://javascript.info/number#more-ways-to-write-a-number

    // All are the same number!
    const oneB_0 = 1200000000
    const oneB_1 = 1_200_000_000
    const oneB_2 = 1.2e9 // You can even do **1.2e-2 for 0.012**
    
  • https://javascript.info/number#tostring-base

    // This is not a typo 😱
    log( 123456..toString(36) ); // 2n9c -> converted to base 36. But notice the 2 dots
    

    If we called a method on a number with just one dot, the compiler would think we are making a mistake and missing numbers after the decimal. Two dots tells the compiler that there is nothing after the decimal point. We can also do (123).toString()

  • 64 bits are used to store a number: 52 of them are used to store the digits, 11 of them store the position of the decimal point, and 1 bit is for the sign.

  • https://javascript.info/number#tests-isfinite-and-isnan

    Number.isNaN is a stricter version of isNaN

    alert( Number.isNaN("str") ); // false, because "str" belongs to the string type, not the number type
    alert( isNaN("str") ); // true, because isNaN converts string "str" into a number and gets NaN as a result of this conversion
    

Strings

  • Link: https://javascript.info/string

  • Ways to make a string with line breaks.

    'Hola \n Soy Fabiano' // Single quotes
    "Hello \n I'm Wesley" // Double quotes
    `
    	Konichiwa
    	Hikaru desu
    ` // Backticks
    
    • We get an Unexpected EOF error if we use ↲ while using quotes

      let a = "Hello
      World"
      
  • Tagged Templates #til #advanced

    • Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)

    • Template tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

      const doIntroduction = function(strings, playerName, favSport) {
      	const [str0, str1] = strings // ["Hello, I'm ", " and I love playing ", ""]
      	return str0 + playerName + str1 + favSport
      }
      
      const name = "Ding"
      const favGame = "Chess"
      
      doIntroduction`Hello, I'm ${name} and I love playing ${favGame}` // Hello, I'm Ding and I love playing Chess
      
    • All of this is allowed

      1. property access
      2. function call
      3. new Function syntax
      4. Another tagged template literal
      console.log`Hello`; // [ 'Hello' ]
      console.log.bind(1, 2)`Hello`; // 2 [ 'Hello' ]
      new Function("console.log(arguments)")`Hello`; // [Arguments] { '0': [ 'Hello' ] }
      
      function recursive(strings, ...values) {
        console.log(strings, values);
        return recursive;
      }
      recursive`Hello``World`;
      // [ 'Hello' ] []
      // [ 'World' ] []
      
    • A simple way to understand this is “the syntax functempLiteral`` breaks down the template literal into an array with two values, [0] having all the string literals and [1] having all the dynamic properties a.k.a ${}

      • Consider the example console.log.bind(null, 1)Hello $2``. This is indeed a complex example but it will help deepen the understanding of what’s happening. The output for this code is
      1
      [
      	["Hello", ""],
      	2
      ]
      
      • When we call console.log.bind(null, 1) it prints 1 onto the console, then the returned console.log function is called with Hello ${2}. The JS engine splits the literal into [["Hello”, “”], 2] which is passed to console.log and it prints it as it is.

Arrays

  • Link: https://javascript.info/array

  • https://javascript.info/array#get-last-elements-with-at

    let fruits = ["Apple", "Orange", "Plum"];
    alert( fruits.at(-1) ); // Plum -> same as fruits[fruits.length-1]
    
  • https://javascript.info/array#internals

    The ways to misuse an array:

    • Add a non-numeric property like arr.test = 5.
    • Make holes, like: add arr[0] and then arr[1000] (and nothing between them).
    • Fill the array in the reverse order, like arr[1000]arr[999] and so on.

    Any of such misuse removes the optimisations the JS engine reserves for an array #anti-pattern

  • https://javascript.info/array#performance 🤯

    Methods push/pop run fast, while shift/unshift are slow. Because the whole array needs to be reindexed in case of shift/unshift

  • https://javascript.info/array#loops

    Using for…in for arrays is not advised for a couple of reasons #anti-pattern

    1. The loop for..in iterates over all properties, not only the numeric ones. If you have a object which behaves like an array (has indexed props and length prop),
    2. The for..in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower.

    Use for..of or the ye oldie for loop


Content Updates

  • 2023-06-19 - init
  • 2023-07-29 - Added contents under "Date and Time" topic
  • 2023-07-29 - Split the whole article into 3 posts for easier consumption