We use cookies to enhance your experience on the site
CodeWorlds

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

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.

1// Different ways to declare strings
2const dinoName = "Tyrannosaurus Rex";
3const warningSign = 'Warning! Do not approach the fence!';
4const locationInfo = `You are in sector B4`;
5
6// Strings can contain special characters
7const multilineWarning = "Warning!
8Do not feed the dinosaurs!";  // 
9 means new line
10
11// String length (number of characters)
12const nameLength = dinoName.length;  // 16
13
14// Joining strings (concatenation)
15const fullWarning = warningSign + " " + dinoName + " is dangerous!";
16
17// Template literals - only with backticks (``)
18const 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:

1const species = "Velociraptor";
2
3// Changing case
4const upperCase = species.toUpperCase();  // "VELOCIRAPTOR"
5const lowerCase = species.toLowerCase();  // "velociraptor"
6
7// Searching in a string
8const hasRaptor = species.includes("raptor");  // true
9const position = species.indexOf("raptor");    // 5 (indices start from 0)
10const startsWith = species.startsWith("Velo"); // true
11const endsWith = species.endsWith("tor");      // true
12
13// Extracting fragments
14const firstFour = species.substring(0, 4);     // "Velo"
15const lastSix = species.slice(-6);             // "raptor"
16
17// Replacing fragments
18const newSpecies = species.replace("Veloci", "Micro"); // "Microraptor"
19
20// Splitting a string into an array
21const announcement = "Attention! All guests please evacuate!";
22const 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.

1// Integers
2const dinoCount = 37;
3const parkSectors = 12;
4
5// Floating-point numbers (decimals)
6const trexHeight = 5.6;  // meters
7const raptorSpeed = 38.5;  // km/h
8
9// Scientific notation
10const atomSize = 1.5e-10;  // 0.00000000015
11const dinosaurCellCount = 3.2e12;  // 3,200,000,000,000
12
13// Infinity and NaN (Not a Number)
14const infinity = Infinity;  // Infinite value
15const negInfinity = -Infinity;  // Negative infinite value
16const 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:

1// Basic arithmetic operations
2const sum = 10 + 5;    // 15 (addition)
3const diff = 10 - 5;   // 5 (subtraction)
4const product = 10 * 5;  // 50 (multiplication)
5const quotient = 10 / 5;  // 2 (division)
6const remainder = 10 % 3;  // 1 (modulo - remainder of division)
7const power = 10 ** 2;  // 100 (exponentiation - 10 to the power of 2)
8
9// Math object for advanced operations
10const roundedHeight = Math.round(trexHeight);  // 6 (rounding)
11const ceilingHeight = Math.ceil(trexHeight);   // 6 (rounding up)
12const floorHeight = Math.floor(trexHeight);    // 5 (rounding down)
13const randomNumber = Math.random();   // Random number between 0 and 1
14const maxSpeed = Math.max(42, 35, 38, 40);  // 42 (highest value)
15const 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:

1const precisionIssue = 0.1 + 0.2;  // We expect 0.3, but get 0.30000000000000004
2
3// Solution - use rounding or scaled constants:
4const fixedResult = Number((0.1 + 0.2).toFixed(1));  // 0.3
5const 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.

1// Basic boolean values
2const fenceActive = true;
3const parkClosed = false;
4
5// Logical expressions return boolean
6const isTRexDangerous = true;
7const isParkOpen = !parkClosed;  // true (negation)
8const isSafeToEnter = fenceActive && isParkOpen;  // true (AND)
9const 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.

1// Using boolean in conditional statements
2if (fenceActive) {
3    console.log("Enclosure secured");
4} else {
5    console.log("WARNING! Enclosure unsecured!");
6    activateEmergencyProtocol();
7}
8
9// Comparison operators return boolean
10const isDangerousSpecies = dinosaurType === "Velociraptor" || dinosaurType === "T-Rex";
11const isHerbivore = dinosaurDiet !== "carnivore";
12const isTooBig = dinosaurHeight > 3;
13const 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.

1// Variable with null value
2let selectedDinosaur = null;  // Currently no dinosaur is selected
3
4// Null is often used as an initial value
5let scannedChip = null;  // Before scanning, the chip contains no data
6
7// Checking if a value is null
8if (selectedDinosaur === null) {
9    console.log("No dinosaur has been selected");
10}
11
12// Null is a falsy value
13if (!selectedDinosaur) {
14    console.log("This will also display for null");
15}

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.

1// Declared but uninitialized variable
2let newDinosaur;  // automatically has the value undefined
3
4// Function without explicit return returns undefined
5function checkEnclosure() {
6    // No return statement
7}
8const result = checkEnclosure();  // result has value undefined
9
10// Checking if a value is undefined
11if (newDinosaur === undefined) {
12    console.log("Dinosaur has not been specified yet");
13}
14
15// undefined is a falsy value
16if (!newDinosaur) {
17    console.log("This will also display for undefined");
18}

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)
1// typeof shows the difference
2typeof null;        // "object" (this is a historical bug in JavaScript)
3typeof undefined;   // "undefined"
4
5// In terms of equality
6null == undefined;  // true (loose equality)
7null === undefined; // false (strict equality)

Symbol and BigInt - Newer Primitive Types

Since ES6 (ES2015), JavaScript has two additional primitive types: Symbol and BigInt.

Symbol - Unique Identifier

1// Creating unique identifiers
2const dinoId = Symbol('dino-id');
3const enclosureId = Symbol('enclosure-id');
4
5// Each Symbol is unique
6const id1 = Symbol('id');
7const id2 = Symbol('id');
8console.log(id1 === id2);  // false, even though they have the same description

BigInt - Large Integers

1// Creating BigInt by adding 'n' at the end of a number or using the BigInt() function
2const dinoGenomeSize = 9007199254740991n;
3const sameBigInt = BigInt(9007199254740991);
4
5// BigInt can represent numbers larger than Number.MAX_SAFE_INTEGER
6console.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:

1typeof "Triceratops";  // "string"
2typeof 42;            // "number"
3typeof true;          // "boolean"
4typeof null;          // "object" (note: this is a historical bug in JavaScript)
5typeof undefined;     // "undefined"
6typeof Symbol();      // "symbol"
7typeof 42n;           // "bigint"
8
9// For functions and objects
10typeof function() {};  // "function"
11typeof {};             // "object"
12typeof [];             // "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.

1// Automatic conversion to string
2"Dinosaur " + 5;  // "Dinosaur 5" (number 5 was converted to string)
3
4// Automatic conversion to number
5"5" - 2;  // 3 (string "5" was converted to number)
6"5" * 2;  // 10 (string "5" was converted to number)
7
8// Automatic conversion to boolean
9if ("Dinosaur") {
10    // This code will execute, because a non-empty string is treated as true
11}
12
13if (0) {
14    // This code will NOT execute, because 0 is treated as false
15}

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
1// Boolean conversion examples
2Boolean(0);        // false
3Boolean("");       // false
4Boolean(null);     // false
5Boolean(undefined);// false
6Boolean(NaN);      // false
7
8Boolean(1);        // true
9Boolean("text");   // true
10Boolean([]);       // true (empty array is truthy)
11Boolean({});       // 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:

1// Converting to string
2String(42);           // "42"
3(42).toString();      // "42"
442 + "";              // "42" (uses implicit conversion)
5
6// Converting to number
7Number("42");         // 42
8parseInt("42", 10);   // 42 (second number is the radix, e.g., 10 for decimal)
9parseFloat("42.5");   // 42.5
10+"42";                // 42 (uses implicit conversion)
11
12// Converting to boolean
13Boolean(1);           // true
14Boolean(0);           // false
15!!"value";            // true (double negation)

Safe Type Checking

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

1// Checking if a variable is a string
2function isString(value) {
3    return typeof value === 'string' || value instanceof String;
4}
5
6// Checking if a variable is a number (with additional NaN check)
7function isNumber(value) {
8    return typeof value === 'number' && !isNaN(value);
9}
10
11// Checking if a variable is a boolean
12function isBoolean(value) {
13    return typeof value === 'boolean';
14}
15
16// Checking if a variable has a null value
17function isNull(value) {
18    return value === null;
19}
20
21// Checking if a variable has an undefined value
22function isUndefined(value) {
23    return typeof value === 'undefined';
24}

Practical Example: Dinosaur Inventory System

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

1// Configuration constants
2const PARK_NAME = "Jurassic Park";
3const MAX_CAPACITY = 50;
4const SECURITY_LEVELS = {
5    LOW: 1,
6    MEDIUM: 2,
7    HIGH: 3,
8    CRITICAL: 4
9};
10
11// Dinosaur inventory system
12function processDinosaurData(dinoId, name, species, height, isDangerous) {
13    // Data type checking
14    if (typeof dinoId !== 'number' || !Number.isInteger(dinoId) || dinoId <= 0) {
15        return "Error: Invalid dinosaur ID";
16    }
17
18    if (typeof name !== 'string' || name.trim() === '') {
19        return "Error: Invalid dinosaur name";
20    }
21
22    if (typeof height !== 'number' || height <= 0) {
23        return "Error: Invalid dinosaur height";
24    }
25
26    if (typeof isDangerous !== 'boolean') {
27        return "Error: Danger parameter must be of type boolean";
28    }
29
30    // Data processing
31    let securityLevel = null;
32
33    if (isDangerous) {
34        securityLevel = height > 3 ? SECURITY_LEVELS.CRITICAL : SECURITY_LEVELS.HIGH;
35    } else {
36        securityLevel = height > 5 ? SECURITY_LEVELS.MEDIUM : SECURITY_LEVELS.LOW;
37    }
38
39    // Preparing dinosaur report
40    const dinoRecord = {
41        id: dinoId,
42        name: name,
43        species: species || "Unknown", // Protection against undefined
44        height: height,
45        dangerous: isDangerous,
46        securityLevel: securityLevel,
47        enclosureType: getEnclosureType(securityLevel),
48        lastUpdated: new Date().toISOString()
49    };
50
51    // Return the report
52    return dinoRecord;
53}
54
55// Helper function
56function getEnclosureType(securityLevel) {
57    switch(securityLevel) {
58        case SECURITY_LEVELS.LOW:
59            return "Open range";
60        case SECURITY_LEVELS.MEDIUM:
61            return "Standard fence";
62        case SECURITY_LEVELS.HIGH:
63            return "Reinforced fence with monitoring";
64        case SECURITY_LEVELS.CRITICAL:
65            return "Isolated high-security enclosure";
66        default:
67            return "Unspecified";
68    }
69}
70
71// Usage example
72const trexData = processDinosaurData(
73    1,
74    "Rexy",
75    "Tyrannosaurus Rex",
76    5.6,
77    true
78);
79
80console.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.

Go to CodeWorlds