Basic Types and Values


Primitive Types

  1. Number Type

    // Number Representation
    let integer = 42;           // Whole number
    let decimal = 3.14;         // Floating-point number
    let scientific = 5e3;       // Scientific notation (5000)
    let hexadecimal = 0xFF;     // Hexadecimal (255)
    let binary = 0b1010;        // Binary representation (10)
    
  2. String Type

    // String Immutability Demonstration
    let str = "immutable";
    str[0] = 'I';  // This won't change the string
    
  3. Boolean Type

    Similar to boolean in any programming language, it has two values true and false

    All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.

  4. Undefined Type

    let string;
    console.log(string); // undefined
    

    undefined represents a variable that has been declared but not assigned a value, automatically set by JavaScript. It is diffrent from null.

  5. Null Type

    null is a special value in JavaScript that developers deliberately use to show a variable is intentionally empty or has no value assigned to it.

  6. Symbol Type ( ES6 ) In JavaScript, a Symbol is a unique and immutable primitive type that creates guaranteed distinct values, primarily used to create non-string property keys and prevent property name collisions in objects

    // guaranteed distinct values
    let sym1 = Symbol("description");
    let sym2 = Symbol("description");
    console.log(sym1 === sym2); // false
    
    // use case in objects to get unique keys
    const uniqueKey = Symbol('description');
    const obj = {
        [uniqueKey]: 'This is a unique property'
    };
    
  7. BigInt Type ( ES2020 )

    let bigNum = 1234567890123456789012345678901234567890n;
    let bigIntValue = BigInt(42);
    

Type checking and coercion

Type of operator

The typeof operator we discussed earlier is used for type checking in JavaScript. It allows you to determine the type of a given variable

Type Coercion

Type Coercion in JavaScript is the process of converting one data type to another, either automatically (implicit) or manually (explicit).

Type conversion methods are explicit ways to convert a value from one type to another. Some common methods include: