JavaScript and TypeScript course ยท Module 1: JavaScript Basics

Basic Data Types (string, number, boolean, null, undefined)

12 min read ยท
In this lesson8

Just as in Jurassic Park we have different dinosaur species, each with unique characteristics and behaviors, in JavaScript we have different data types, each serving specific purposes. Understanding these types is crucial for effective programming - it's like knowing the differences between a Velociraptor and a Triceratops for a park employee.

Primitive Types

JavaScript has five main primitive types: string, number, boolean, null, and undefined. These are the fundamental "species" in our digital park.

1. String - Text

The string type represents text - a sequence of characters enclosed in single ('), double ("), or backtick (`) quotes. It's like information signs in Jurassic Park that convey important messages to visitors.

// Different ways to declare strings
const dinoName = "Tyrannosaurus Rex";
const warningSign = 'Warning! Do not approach the fence!';
const locationInfo = `You are in sector B4`;

// Strings can contain special characters
const multilineWarning = "Warning!\nDo not feed the dinosaurs!";  // \n means new line

// String length (number of characters)
const nameLength = dinoName.length;  // 17

// Joining strings (concatenation)
const fullWarning = warningSign + " " + dinoName + " is dangerous!";

// Template literals - only with backticks (``)
const modernWarning = `${warningSign} ${dinoName} is dangerous!`;

Strings are like the universal language of communication in the park - they serve to display information, send messages, and label resources.

String Methods

Strings in JavaScript have built-in methods that allow manipulation, similar to how park employees have tools for managing exhibits:

const species = "Velociraptor";

// Changing case
const upperCase = species.toUpperCase();  // "VELOCIRAPTOR"
const lowerCase = species.toLowerCase();  // "velociraptor"

// Searching in a string
const hasRaptor = species.includes("raptor");  // true
const position = species.indexOf("raptor");    // 6 (indices start from 0)
const startsWith = species.startsWith("Velo"); // true
const endsWith = species.endsWith("tor");      // true

// Extracting fragments
const firstFour = species.substring(0, 4);     // "Velo"
const lastSix = species.slice(-6);             // "raptor"

// Replacing fragments
const newSpecies = species.replace("Veloci", "Micro"); // "Microraptor"

// Splitting a string into an array
const announcement = "Attention! All guests please evacuate!";
const words = announcement.split(" ");  // ["Attention!", "All", "guests", ...]

2. Number - Numbers

The number type represents both integers and floating-point numbers (decimals). Unlike many other programming languages, JavaScript doesn't distinguish between these two types - they are all simply number.

It's like the numerical system in the park used for everything - from counting dinosaurs to measuring their weight or height.

// Integers
const dinoCount = 37;
const parkSectors = 12;

// Floating-point numbers (decimals)
const trexHeight = 5.6;  // meters
const raptorSpeed = 38.5;  // km/h

// Scientific notation
const atomSize = 1.5e-10;  // 0.00000000015
const dinosaurCellCount = 3.2e12;  // 3,200,000,000,000

// Infinity and NaN (Not a Number)
const infinity = Infinity;  // Infinite value
const negInfinity = -Infinity;  // Negative infinite value
const notANumber = NaN;  // Result of an invalid mathematical operation, e.g., 0/0

Number Operations

Numbers in JavaScript support all standard mathematical operations, similar to how scientists in the park perform various calculations:

// Basic arithmetic operations
const sum = 10 + 5;    // 15 (addition)
const diff = 10 - 5;   // 5 (subtraction)
const product = 10 * 5;  // 50 (multiplication)
const quotient = 10 / 5;  // 2 (division)
const remainder = 10 % 3;  // 1 (modulo - remainder of division)
const power = 10 ** 2;  // 100 (exponentiation - 10 to the power of 2)

// Math object for advanced operations
const roundedHeight = Math.round(trexHeight);  // 6 (rounding)
const ceilingHeight = Math.ceil(trexHeight);   // 6 (rounding up)
const floorHeight = Math.floor(trexHeight);    // 5 (rounding down)
const randomNumber = Math.random();   // Random number between 0 and 1
const maxSpeed = Math.max(42, 35, 38, 40);  // 42 (highest value)
const sqrtValue = Math.sqrt(25);  // 5 (square root)

Caution with Floating-Point Precision

In JavaScript (and many other languages), floating-point numbers can lead to unexpected results, similar to unpredictable dinosaur behaviors:

const precisionIssue = 0.1 + 0.2;  // We expect 0.3, but get 0.30000000000000004

// Solution - use rounding or scaled constants:
const fixedResult = Number((0.1 + 0.2).toFixed(1));  // 0.3
const scaledResult = (0.1 * 10 + 0.2 * 10) / 10;  // 0.3

3. Boolean - Logical Values

The boolean type has only two possible values: true or false. It's like an alarm system in the park that can be on or off.

// Basic boolean values
const fenceActive = true;
const parkClosed = false;

// Logical expressions return boolean
const isTRexDangerous = true;
const isParkOpen = !parkClosed;  // true (negation)
const isSafeToEnter = fenceActive && isParkOpen;  // true (AND)
const needsAttention = !fenceActive || parkClosed;  // false (OR)

Boolean values are crucial for decision-making in programs - similar to security systems in the park that decide whether to open a gate, trigger an alarm, or evacuate a sector.

// Using boolean in conditional statements
if (fenceActive) {
    console.log("Enclosure secured");
} else {
    console.log("WARNING! Enclosure unsecured!");
    activateEmergencyProtocol();
}

// Comparison operators return boolean
const isDangerousSpecies = dinosaurType === "Velociraptor" || dinosaurType === "T-Rex";
const isHerbivore = dinosaurDiet !== "carnivore";
const isTooBig = dinosaurHeight > 3;
const isInRange = visitorDistance >= 50;

4. null - Intentional Absence of Value

The value null represents an intentional absence of value - it is an explicit indication that a variable contains no value. It's like an empty enclosure in the park, specially prepared, but currently without a dinosaur.

// Variable with null value
let selectedDinosaur = null;  // Currently no dinosaur is selected

// Null is often used as an initial value
let scannedChip = null;  // Before scanning, the chip contains no data

// Checking if a value is null
if (selectedDinosaur === null) {
    console.log("No dinosaur has been selected");
}

// Null is a falsy value
if (!selectedDinosaur) {
    console.log("This will also display for null");
}

5. undefined - Undefined Value

The value undefined means that a variable has been declared but has not been assigned any value. It's like an undeveloped plot in the park - it exists, but its purpose has not been determined yet.

// Declared but uninitialized variable
let newDinosaur;  // automatically has the value undefined

// Function without explicit return returns undefined
function checkEnclosure() {
    // No return statement
}
const result = checkEnclosure();  // result has value undefined

// Checking if a value is undefined
if (newDinosaur === undefined) {
    console.log("Dinosaur has not been specified yet");
}

// undefined is a falsy value
if (!newDinosaur) {
    console.log("This will also display for undefined");
}

Differences Between null and undefined

Although both types represent "lack of value," there are important differences between them:

  • null is an intentional absence of value (like an empty enclosure)
  • undefined is an unintentional absence of value (like an unassigned spot)
// typeof shows the difference
typeof null;        // "object" (this is a historical bug in JavaScript)
typeof undefined;   // "undefined"

// In terms of equality
null == undefined;  // true (loose equality)
null === undefined; // false (strict equality)

Symbol and BigInt - Newer Primitive Types

Newer versions added two more primitive types: Symbol (ES2015) and BigInt (ES2020). Together with the five types above, JavaScript has seven primitive types.

Symbol - Unique Identifier

// Creating unique identifiers
const dinoId = Symbol('dino-id');
const enclosureId = Symbol('enclosure-id');

// Each Symbol is unique
const id1 = Symbol('id');
const id2 = Symbol('id');
console.log(id1 === id2);  // false, even though they have the same description

BigInt - Large Integers

// Creating BigInt by adding 'n' at the end of a number or using the BigInt() function
const dinoGenomeSize = 9007199254740991n;
const sameBigInt = BigInt(9007199254740991);

// BigInt can represent numbers larger than Number.MAX_SAFE_INTEGER
console.log(Number.MAX_SAFE_INTEGER);  // 9007199254740991

Type Checking

To identify the type of a given value (similar to identifying a dinosaur species), we can use the typeof operator:

typeof "Triceratops";  // "string"
typeof 42;            // "number"
typeof true;          // "boolean"
typeof null;          // "object" (note: this is a historical bug in JavaScript)
typeof undefined;     // "undefined"
typeof Symbol();      // "symbol"
typeof 42n;           // "bigint"

// For functions and objects
typeof function() {};  // "function"
typeof {};             // "object"
typeof [];             // "object" (arrays are objects in JavaScript)

Type Coercion

JavaScript automatically converts types during operations, which can sometimes lead to unexpected results - similar to the unexpected behavior of hybrid dinosaurs in the park.

// Automatic conversion to string
"Dinosaur " + 5;  // "Dinosaur 5" (number 5 was converted to string)

// Automatic conversion to number
"5" - 2;  // 3 (string "5" was converted to number)
"5" * 2;  // 10 (string "5" was converted to number)

// Automatic conversion to boolean
if ("Dinosaur") {
    // This code will execute, because a non-empty string is treated as true
}

if (0) {
    // This code will NOT execute, because 0 is treated as false
}

Falsy and Truthy Values

In JavaScript, every value can be converted to boolean. Values automatically converted to false are called "falsy," and those converted to true are called "truthy."

Falsy values:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

All other values are truthy, including:

  • true
  • Any number other than 0 (including negative and fractions)
  • Any non-empty string
  • Any object, array, and function
// Boolean conversion examples
Boolean(0);        // false
Boolean("");       // false
Boolean(null);     // false
Boolean(undefined);// false
Boolean(NaN);      // false

Boolean(1);        // true
Boolean("text");   // true
Boolean([]);       // true (empty array is truthy)
Boolean({});       // true (empty object is truthy)

Explicit Type Conversion

To avoid unexpected results, it's recommended to explicitly convert types - similar to how in Jurassic Park it's always better to have full control over the dinosaurs:

// Converting to string
String(42);           // "42"
(42).toString();      // "42"
42 + "";              // "42" (uses implicit conversion)

// Converting to number
Number("42");         // 42
parseInt("42", 10);   // 42 (second number is the radix, e.g., 10 for decimal)
parseFloat("42.5");   // 42.5
+"42";                // 42 (uses implicit conversion)

// Converting to boolean
Boolean(1);           // true
Boolean(0);           // false
!!"value";            // true (double negation)

Safe Type Checking

In real applications, just as in park safety protocols, it's worth applying rigorous type checking:

// Checking if a variable is a string
function isString(value) {
    return typeof value === 'string' || value instanceof String;
}

// Checking if a variable is a number (with additional NaN check)
function isNumber(value) {
    return typeof value === 'number' && !isNaN(value);
}

// Checking if a variable is a boolean
function isBoolean(value) {
    return typeof value === 'boolean';
}

// Checking if a variable has a null value
function isNull(value) {
    return value === null;
}

// Checking if a variable has an undefined value
function isUndefined(value) {
    return typeof value === 'undefined';
}

Practical Example: Dinosaur Inventory System

The following example illustrates the use of different data types in a complex system:

// Configuration constants
const PARK_NAME = "Jurassic Park";
const MAX_CAPACITY = 50;
const SECURITY_LEVELS = {
    LOW: 1,
    MEDIUM: 2,
    HIGH: 3,
    CRITICAL: 4
};

// Dinosaur inventory system
function processDinosaurData(dinoId, name, species, height, isDangerous) {
    // Data type checking
    if (typeof dinoId !== 'number' || !Number.isInteger(dinoId) || dinoId <= 0) {
        return "Error: Invalid dinosaur ID";
    }

    if (typeof name !== 'string' || name.trim() === '') {
        return "Error: Invalid dinosaur name";
    }

    if (typeof height !== 'number' || height <= 0) {
        return "Error: Invalid dinosaur height";
    }

    if (typeof isDangerous !== 'boolean') {
        return "Error: Danger parameter must be of type boolean";
    }

    // Data processing
    let securityLevel = null;

    if (isDangerous) {
        securityLevel = height > 3 ? SECURITY_LEVELS.CRITICAL : SECURITY_LEVELS.HIGH;
    } else {
        securityLevel = height > 5 ? SECURITY_LEVELS.MEDIUM : SECURITY_LEVELS.LOW;
    }

    // Preparing dinosaur report
    const dinoRecord = {
        id: dinoId,
        name: name,
        species: species || "Unknown", // Protection against undefined
        height: height,
        dangerous: isDangerous,
        securityLevel: securityLevel,
        enclosureType: getEnclosureType(securityLevel),
        lastUpdated: new Date().toISOString()
    };

    // Return the report
    return dinoRecord;
}

// Helper function
function getEnclosureType(securityLevel) {
    switch(securityLevel) {
        case SECURITY_LEVELS.LOW:
            return "Open range";
        case SECURITY_LEVELS.MEDIUM:
            return "Standard fence";
        case SECURITY_LEVELS.HIGH:
            return "Reinforced fence with monitoring";
        case SECURITY_LEVELS.CRITICAL:
            return "Isolated high-security enclosure";
        default:
            return "Unspecified";
    }
}

// Usage example
const trexData = processDinosaurData(
    1,
    "Rexy",
    "Tyrannosaurus Rex",
    5.6,
    true
);

console.log(trexData);

Summary

  1. String - represents text

    • Like information signs in the park
    • Enclosed in ', ", or `
    • Has many built-in methods (e.g., toUpperCase(), indexOf())
  2. Number - represents integers and floating-point numbers

    • Like the numerical system in the park
    • Supports all standard mathematical operations
    • Be careful with floating-point precision
  3. Boolean - logical values true or false

    • Like an alarm system (on/off)
    • Foundation for decision-making (conditional statements)
    • Also created as a result of comparison operations
  4. null - intentional absence of value

    • Like an empty, prepared enclosure
    • Explicitly set by the programmer
    • Represents "nothing" or "unknown"
  5. undefined - undefined value

    • Like a yet-unassigned spot in the park
    • Appears automatically for uninitialized variables
    • Also the default result of a function without return

Understanding data types in JavaScript is the foundation of effective programming - just as knowing different dinosaur species is crucial for Jurassic Park employees. Each type has its applications, limitations, and behaviors that you need to know to avoid unexpected "incidents" in your code!

In the next lesson, we will discuss type conversion and operations on data types - like learning safe and effective work with different dinosaur species in the park.

Code for this lesson: index.js
// Diagnostic System - Functions
// Exercise: Creating and calling functions

// Function declaration
function checkDinosaur(name, health) {
  console.log("Examining: " + name);
  if (health > 80) {
    return name + " - status: EXCELLENT";
  } else if (health > 50) {
    return name + " - status: GOOD";
  } else {
    return name + " - status: NEEDS CARE";
  }
}

// Function call
console.log(checkDinosaur("T-Rex", 95));
console.log(checkDinosaur("Raptor", 72));
console.log(checkDinosaur("Brachio", 45));

// Function with default value
function feedDinosaur(name, amount = 50) {
  console.log(name + " fed: " + amount + " kg");
}

feedDinosaur("T-Rex", 200);
feedDinosaur("Compy"); // will use default value 50

// Your task:
// 1. Create a function calculateAge(birthYear) that calculates age
// 2. Create a function with a default parameter
// 3. Call them with different arguments

// Your code here:

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What values can the boolean type hold in JavaScript?

  2. 2. What will typeof 42 return in JavaScript?

Hands-on tasks in the game

  • Code editor

    Declare three variables describing a DNA sample: the species name (string), the weight in kilograms (number) and whether the dinosaur is a carnivore (boolean). Display each variable in the console together with its type, using typeof.

  1. QuestionBoolean Type
  2. Questiontypeof Operator
  3. Coding taskPractice: Data Types

Useful articles