JavaScript and TypeScript course ยท Module 1: JavaScript Basics

Type Conversion and Operations on Types

15 min read ยท
In this lesson8

In Jurassic Park, scientists often need to transform data from one form to another - translating DNA sequences into dinosaur attributes, converting measurements between different systems, or analyzing animal behavior. Similarly in JavaScript, type conversion and operations on data types are fundamental skills that allow for effective data manipulation.

Implicit Type Conversion (Type Coercion)

JavaScript is dynamically typed (values have types, variables do not) and weakly typed: when an operation needs it, it converts values to another type on its own. It's like the automatic adaptive systems in Jurassic Park that adjust to changing conditions - sometimes convenient, but sometimes surprising.

Conversion in Arithmetic Operations

When JavaScript performs arithmetic operations, it tries to automatically convert values to numbers:

// String + Number -> String (concatenation)
"Velociraptor " + 3;  // "Velociraptor 3"

// String - Number -> Number
"50" - 10;  // 40 (string "50" is converted to a number)

// String * Number -> Number
"5" * 4;    // 20 (string "5" is converted to a number)

// String / Number -> Number
"20" / 5;   // 4 (string "20" is converted to a number)

Notice the special case of the + operator, which for strings acts as a concatenation (joining) operator, not addition. It's like observing that velociraptors always hunt in packs - knowledge that can save your life!

Conversion in Comparison Operations

When comparing values of different types using the == (loose equality) operator, JavaScript tries to convert them to a common type:

// Number == String
5 == "5";     // true (string "5" is converted to number 5)

// Boolean == Number
true == 1;    // true (true is converted to 1)
false == 0;   // true (false is converted to 0)

// null == undefined
null == undefined;  // true (special case in the specification)

// Object == Primitive
[1] == 1;     // true ([1] is converted to "1", then to 1)

Such behavior resembles "intuitive" observations in the park - "This enclosure looks the same as that one" - which can be misleading if you don't know the details.

Conversion in Logical Operations

Logical operators &&, || and ! can work with values of any type, implicitly converting them to boolean:

// The ! (negation) operator converts a value to boolean and negates it
!0;           // true (0 is converted to false, then negated)
!"Dino";      // false ("Dino" is converted to true, then negated)

// The && and || operators can return original values, not just booleans
"T-Rex" && "Raptor";  // "Raptor" (if the first operand is truthy, returns the second)
0 || "Backup";        // "Backup" (if the first operand is falsy, returns the second)

This logic is like the protocol in the park: "If the fence is working AND it's tall enough, the dinosaur won't escape" - both conditions must be met for the entire statement to be true.

Explicit Type Conversion

To avoid unexpected results from implicit conversion, it's often better to explicitly convert values to the desired type. It's like precise laboratory protocols in Jurassic Park - exactly defined procedures yielding predictable results.

Conversion to String

// Method #1: String() function
String(42);         // "42"
String(true);       // "true"
String(null);       // "null"
String(undefined);  // "undefined"
String({ name: "T-Rex" });  // "[object Object]"
String([1, 2, 3]);  // "1,2,3"

// Method #2: toString() method
(42).toString();    // "42"
true.toString();    // "true"
[1, 2, 3].toString();  // "1,2,3"
// null.toString();    // Error! Null and undefined don't have the toString() method

// Method #3: Concatenation with an empty string
42 + "";            // "42"
true + "";          // "true"
null + "";          // "null"

Conversion to Number

// Method #1: Number() function
Number("42");       // 42
Number("42px");     // NaN (cannot convert the entire string to a number)
Number(true);       // 1
Number(false);      // 0
Number(null);       // 0
Number(undefined);  // NaN
Number([1]);        // 1 (single-element array is converted to its element)
Number([1, 2]);     // NaN (multi-element array cannot be converted)

// Method #2: parseInt() and parseFloat() functions
parseInt("42");     // 42
parseInt("42px");   // 42 (converts until it encounters an invalid character)
parseInt("3.14");   // 3 (converts only the integer part)
parseFloat("3.14"); // 3.14 (converts the floating-point part)

// Method #3: Unary + and - operators
+"42";              // 42
-"42";              // -42
+true;              // 1

Conversion to Boolean

// Method #1: Boolean() function
Boolean(42);        // true
Boolean(0);         // false
Boolean("");        // false
Boolean("text");    // true
Boolean(null);      // false
Boolean(undefined); // false
Boolean({});        // true (every object is truthy)

// Method #2: Double negation !!
!!42;               // true
!!0;                // false
!!"text";           // true
!!null;             // false

Conversion Tables

The following tables are like dinosaur genetic charts in the park - they show exactly what happens during conversion between different types.

Conversion to String

Input TypeInput ExampleString Conversion Result
Number42"42"
Booleantrue"true"
nullnull"null"
undefinedundefined"undefined"
Array[1, 2, 3]"1,2,3"
Object{name: "Rex"}"[object Object]"
Functionfunction(){}"function(){}"

Conversion to Number

Input TypeInput ExampleNumber Conversion Result
String"42"42
String" 42 "42 (whitespace is removed)
String"42px"NaN
String""0 (empty string)
Booleantrue1
Booleanfalse0
nullnull0
undefinedundefinedNaN
Array[]0 (empty array)
Array[5]5 (single-element array)
Array[1, 2]NaN (multiple elements)
Object{}NaN

Conversion to Boolean

Input TypeInput ExampleBoolean Conversion Result
Number42true
Number0false
NumberNaNfalse
String"text"true
String""false
nullnullfalse
undefinedundefinedfalse
Object{} (any)true
Array[] (any)true

Operations on Data Types

Now let's look at detailed operations on individual data types. It's like specialized procedures for different dinosaur species.

String Operations

Strings in JavaScript offer a rich set of methods for text manipulation:

const parkName = "Jurassic Park";

// String length
parkName.length;  // 13

// Accessing individual characters
parkName[0];        // "J"
parkName.charAt(0); // "J" (alternative method)

// Searching for substrings
parkName.indexOf("Park");      // 9 (index where "Park" begins)
parkName.startsWith("Jur");    // true
parkName.endsWith("Park");     // true
parkName.includes("assic");    // true

// Changing case
parkName.toUpperCase();        // "JURASSIC PARK"
parkName.toLowerCase();        // "jurassic park"

// Extracting fragments
parkName.substring(0, 8);      // "Jurassic"
parkName.slice(-4);            // "Park" (counts from the end)

// Replacing fragments
parkName.replace("Jurassic", "Dinosaur");  // "Dinosaur Park"

// Splitting a string into an array
parkName.split(" ");           // ["Jurassic", "Park"]

// Removing whitespace
"  Danger Zone  ".trim();      // "Danger Zone"

// Joining strings
"Welcome".concat(" to ", parkName); // "Welcome to Jurassic Park"

// Repeating a string
"Roar! ".repeat(3);            // "Roar! Roar! Roar! "

Number Operations

JavaScript offers many possibilities for working with numbers, both directly on values and through the Math object:

// Basic arithmetic operations
5 + 3;    // 8 (addition)
5 - 3;    // 2 (subtraction)
5 * 3;    // 15 (multiplication)
5 / 3;    // 1.6666666666666667 (division)
5 % 3;    // 2 (modulo - remainder of division)
5 ** 3;   // 125 (exponentiation - 5 to the power of 3)

// Increment and decrement
let dinoCount = 5;
dinoCount++;  // dinoCount is now 6
dinoCount--;  // dinoCount is back to 5

// Assignment and operation operators
dinoCount += 3;  // Same as: dinoCount = dinoCount + 3
dinoCount *= 2;  // Same as: dinoCount = dinoCount * 2

// Math object for advanced operations
Math.abs(-5);            // 5 (absolute value)
Math.round(4.7);         // 5 (rounding to the nearest integer)
Math.ceil(4.1);          // 5 (rounding up)
Math.floor(4.9);         // 4 (rounding down)
Math.max(3, 7, 2, 4);    // 7 (finding the maximum)
Math.min(3, 7, 2, 4);    // 2 (finding the minimum)
Math.pow(2, 3);          // 8 (exponentiation - 2 to the power of 3)
Math.sqrt(16);           // 4 (square root)
Math.sin(0);             // 0 (sine)
Math.cos(0);             // 1 (cosine)
Math.random();           // Random number from 0 (inclusive) to 1 (exclusive)

// Generating a random number within a range
function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
getRandom(1, 10);  // Random number from 1 to 10

// Formatting numbers
const height = 5.678934;
height.toFixed(2);           // "5.68" (two decimal places, returns a string)
height.toPrecision(3);       // "5.68" (three significant digits, returns a string)
height.toString(2);          // "101.1010110111001110100111100101111000100100011110001" (binary representation)
(1234567).toLocaleString();  // "1,234,567" (formatting with separators, depends on locale)

Boolean Operations

Although the boolean type has only two possible values, there are many logical operations:

// Comparison operators
5 > 3;              // true (greater than)
5 >= 5;             // true (greater than or equal)
3 < 5;              // true (less than)
3 <= 3;             // true (less than or equal)
5 == "5";           // true (loose equality - different types are converted)
5 === "5";          // false (strict equality - types must match)
5 != "6";           // true (loose inequality)
5 !== "5";          // true (strict inequality)

// Logical operators
true && true;       // true (logical AND - both conditions must be true)
true && false;      // false
true || false;      // true (logical OR - at least one condition must be true)
false || false;     // false
!true;              // false (logical NOT - negation)
!false;             // true

// Complex conditions
const isSafe = fenceActive && powerLevel > 5000 && !stormApproaching;
const needsEvacuation = alarmTriggered || dinoEscaped || stormStrength > 8;

Operations on null and undefined

Despite the limited possibilities for direct operations on null and undefined, there are useful patterns for working with them:

// The || operator for default values (note: it also replaces 0 and an empty string)
const visitorName = userName || "Guest";  // Use userName if it exists, otherwise "Guest"

// Nullish coalescing operator (??) - available in newer JS versions
const count = dinoCount ?? 0;  // Use dinoCount if not null/undefined, otherwise 0

// Optional chaining (?.) - available in newer JS versions
const species = dinosaur?.species;  // Safely access the property, even if dinosaur is null/undefined

Interesting and Tricky Type Conversion Cases

Some type conversions in JavaScript can be surprising, similar to unusual dinosaur behavior after a storm:

// Strange cases of loose equality (==)
[] == '';            // true (empty array is converted to empty string)
[1] == 1;            // true (array [1] is converted to string "1", then to number 1)
[1, 2] == '1,2';     // true (array [1, 2] is converted to string "1,2")
true == '1';         // true (true is converted to 1, and '1' to 1)
false == '0';        // true (false is converted to 0, and '0' to 0)
null == undefined;   // true (special case in the specification)
'' == 0;             // true (empty string is converted to 0)

// Operations with NaN
NaN == NaN;          // false (NaN is not equal to anything, not even itself)
Number.isNaN(NaN);   // true (the proper way to check for NaN)

// Operations with objects
const obj1 = {}, obj2 = {};
obj1 == obj2;        // false (objects are compared by reference, not content)
obj1 === obj2;       // false (objects are compared by reference, not content)

// Operations on arrays
[] + [];             // "" (arrays are converted to strings, then joined)
[] + {};             // "[object Object]" (object is converted to string)
{} + [];             // 0 (empty {} is treated as a code block, and +[] is converted to a number)

Best Practices

To avoid surprises when working with data types, it's worth following these rules - they're like safety protocols in Jurassic Park:

1. Use strict comparison (===, !==)

// BAD
if (dinoCount == "5") {  // Will work, but can lead to bugs

// GOOD
if (dinoCount === 5) {  // Clearly indicates that dinoCount should be a number

2. Explicitly convert types when needed

// BAD
const totalVisitors = visitorCount + newVisitors;  // May give incorrect results if either variable is a string

// GOOD
const totalVisitors = Number(visitorCount) + Number(newVisitors);  // Explicit conversion to numbers

3. Use appropriate type-checking methods

// BAD
if (typeof height == "number" && !isNaN(height)) {  // Works, but is imprecise

// GOOD
function isValidNumber(value) {
    return typeof value === 'number' && !isNaN(value) && isFinite(value);
}
if (isValidNumber(height)) {

4. Be careful with object operations

// BAD
if (dinosaur == otherDinosaur) {  // Compares references, not content

// GOOD
function isEqual(obj1, obj2) {
    return JSON.stringify(obj1) === JSON.stringify(obj2);  // For simple objects
}
if (isEqual(dinosaur, otherDinosaur)) {

5. Use nullish coalescing (??) and optional chaining (?.) operators

// INSTEAD OF
const safeVisitorCount = visitorCount !== null && visitorCount !== undefined ? visitorCount : 0;
const speciesName = dinosaur && dinosaur.species ? dinosaur.species : "Unknown";

// BETTER (in newer JS)
const safeVisitorCount = visitorCount ?? 0;
const speciesName = dinosaur?.species ?? "Unknown";

Practical Example: Processing Dinosaur Data

The following example shows how to apply type operations in a practical scenario:

// Data coming from various sources (API simulation, forms, CSV files)
const rawDinoData = [
    { id: "1", name: "Rexy", species: "T-Rex", height: "5.6", dangerous: "true", lastFed: "2023-05-15T08:30:00" },
    { id: 2, name: "Blue", species: "Velociraptor", height: "1.8", dangerous: true, lastFed: "2023-05-15T09:15:00" },
    { id: "3", name: "Spike", species: "Stegosaurus", height: 4.2, dangerous: "false", lastFed: null },
    { id: "4", name: "Cera", species: "Triceratops", height: "unknown", dangerous: false, lastFed: "invalid-date" }
];

// Function to normalize and validate data
function processDinosaurData(dinoList) {
    // Prepare the normalized array
    const processedData = [];

    // Process each element
    for (let i = 0; i < dinoList.length; i++) {
        const dino = dinoList[i];

        // Normalize ID
        const id = Number(dino.id);
        if (isNaN(id) || id <= 0) {
            console.warn(`Skipped dinosaur with invalid ID: ${dino.id}`);
            continue;
        }

        // Normalize name
        const name = String(dino.name).trim();
        if (name === "") {
            console.warn(`Skipped dinosaur without a name, ID: ${id}`);
            continue;
        }

        // Normalize species
        const species = String(dino.species).trim() || "Unknown";

        // Normalize height
        let height;
        if (dino.height === "unknown" || dino.height === undefined) {
            height = null;
        } else {
            height = Number(dino.height);
            if (isNaN(height)) {
                console.warn(`Invalid height for ${name}, set to null`);
                height = null;
            }
        }

        // Normalize dangerous flag
        let dangerous;
        if (typeof dino.dangerous === 'string') {
            dangerous = dino.dangerous.toLowerCase() === 'true';
        } else {
            dangerous = Boolean(dino.dangerous);
        }

        // Normalize last feeding date
        let lastFed = null;
        if (dino.lastFed) {
            const date = new Date(dino.lastFed);
            if (!isNaN(date.getTime())) {
                lastFed = date;
            } else {
                console.warn(`Invalid feeding date for ${name}`);
            }
        }

        // Additional calculations
        const securityLevel = dangerous ? (height > 3 ? "High" : "Medium") : "Low";
        const daysFromLastFeed = lastFed ? Math.floor((new Date() - lastFed) / (1000 * 60 * 60 * 24)) : null;

        // Add the normalized dinosaur to the result array
        processedData.push({
            id,
            name,
            species,
            height,
            dangerous,
            lastFed,
            securityLevel,
            daysFromLastFeed,
            needsFeeding: daysFromLastFeed === null || daysFromLastFeed > 1
        });
    }

    return processedData;
}

// Using the function
const normalizedDinos = processDinosaurData(rawDinoData);
console.log(normalizedDinos);

// Additional data processing
const dangerousDinos = normalizedDinos.filter(dino => dino.dangerous);
const withHeight = normalizedDinos.filter(dino => dino.height !== null);
const avgHeight = withHeight.reduce((sum, dino) => sum + dino.height, 0) / withHeight.length;
const dinosBySecurityLevel = normalizedDinos.reduce((groups, dino) => {
    groups[dino.securityLevel] = groups[dino.securityLevel] || [];
    groups[dino.securityLevel].push(dino);
    return groups;
}, {});

This example shows how to handle different data types, convert them, validate them, and normalize them - all fundamental operations that Jurassic Park scientists would need to perform on daily data.

Summary

Type conversion and operations on data types in JavaScript is a broad topic that requires understanding many nuances. The key aspects are:

  1. Implicit conversion - JavaScript automatically converts types in many contexts

    • Can lead to unexpected results
    • Is convenient but sometimes dangerous
  2. Explicit conversion - Controlled type transformation

    • String(), Number(), Boolean() - conversion functions
    • toString(), parseInt(), parseFloat() - specialized methods and functions
    • !! - quick conversion to boolean
  3. Operations on individual types

    • Strings have a rich set of methods for text manipulation
    • Numbers can be processed using operators and the Math object
    • Boolean values are the foundation for conditional statements
    • Null and undefined have special rules in operations
  4. Best practices

    • Using strict comparison (===, !==)
    • Explicitly converting types where needed
    • Using appropriate checking functions

Just as in Jurassic Park, where different dinosaur species require different handling protocols, in JavaScript different data types require the appropriate approach. Knowledge of conversion rules and type operations enables effective and safe data manipulation - the foundation of every JavaScript application.

In the next lesson, we will look at arithmetic and assignment operators, which allow for more advanced calculations - essential for managing resources in such a complex undertaking as Jurassic Park.

Code for this lesson: index.js
// Type conversion and type operations
// Experiment with implicit and explicit type conversion in JavaScript

// === Implicit conversion (Type Coercion) ===
console.log("=== Implicit conversion ===");

// String + Number -> concatenation
console.log("Dinosaurs: " + 5); // "Dinosaurs: 5"
console.log("5" + 3);            // "53" (string!)

// String - Number -> Number
console.log("10" - 3);   // 7
console.log("5" * 2);    // 10

// Boolean in operations
console.log(true + 1);   // 2
console.log(false + 1);  // 1

// === Explicit conversion ===
console.log("\n=== Explicit conversion ===");

// To Number
console.log(Number("42"));       // 42
console.log(Number("abc"));      // NaN
console.log(parseInt("100px"));  // 100
console.log(parseFloat("3.14m")); // 3.14

// To String
console.log(String(42));         // "42"
console.log(String(true));       // "true"
console.log((255).toString(16)); // "ff" (hex)

// To Boolean
console.log(Boolean(0));         // false
console.log(Boolean(""));        // false
console.log(Boolean("text"));    // true
console.log(Boolean(1));         // true

// === typeof operator ===
console.log("\n=== typeof ===");
console.log(typeof 42);          // "number"
console.log(typeof "text");      // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object" (historical bug!)

// Your task:
// 1. Check the result "5" + 3 vs "5" - 3
// 2. Use Number() to convert a string to a number
// 3. Check typeof for different values

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 will the expression Number('hello') return in JavaScript?

  2. 2. What will the expression '5' - 2 return in JavaScript?

  3. 3. Which method of explicit string-to-number conversion is INCORRECT?

  4. 4. Which of the following values is NOT a falsy value in JavaScript?

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the template literal elements:

  1. QuestionType Conversion - Number()
  2. QuestionImplicit Type Conversion
  3. QuestionExplicit Conversion to Number
  4. Put in orderTemplate Literal Syntax
  5. QuestionFalsy Values in JavaScript

Useful articles