Academic Block

Database Basics and JS (CRUD) Get Certified

Almost every application is built around four core operations: CREATE, READ, UPDATE, and DELETE — commonly called CRUD.

In this lesson we build a simple in-memory database using a plain JavaScript array and implement each CRUD operation as a clean, reusable function.

Setting Up an In-Memory Database

What this code does: Creates an empty array that will act as our database and a counter for unique IDs.

let users = [];
let nextId = 1;

console.log("Database initialized:", users);
console.log("Next ID will be:", nextId);

CREATE – Adding a Record

What this code does: Creates a new user object with a unique ID and adds it to the database array.

let users = [];
let nextId = 1;

function createUser(data) {
    const user = { id: nextId++, ...data };
    users.push(user);
    return user;
}

const michael = createUser({ name: "Michael", age: 28 });
const david   = createUser({ name: "David", age: 32 });

console.log("Created users:");
console.log(users);

READ – Finding a Single Record

What this code does: Uses find() to return the first matching record or undefined if nothing is found.

let users = [
    { id: 1, name: "Michael", age: 28 },
    { id: 2, name: "David", age: 32 }
];

function findUserById(id) {
    return users.find(user => user.id === id);
}

console.log("User with id 1:", findUserById(1));
console.log("User with id 999:", findUserById(999));

READ – Getting All Records

What this code does: Returns the entire collection of users from the database.

let users = [
    { id: 1, name: "Michael", age: 28 },
    { id: 2, name: "David", age: 32 },
    { id: 3, name: "Emily", age: 24 }
];

function getAllUsers() {
    return users;
}

console.log("All users:", getAllUsers());

UPDATE – Modifying a Record

What this code does: Finds a user by ID and merges the new values into the existing record using Object.assign().

let users = [
    { id: 1, name: "Michael", age: 28 },
    { id: 2, name: "David", age: 32 }
];

function findUserById(id) {
    return users.find(user => user.id === id);
}

function updateUser(id, updates) {
    const user = findUserById(id);
    if (!user) return null;

    Object.assign(user, updates);
    return user;
}

console.log("Before update:", findUserById(1));
updateUser(1, { age: 29 });
console.log("After update:", findUserById(1));

DELETE – Removing a Record

What this code does: Locates the user by ID and removes it from the array with splice().

let users = [
    { id: 1, name: "Michael", age: 28 },
    { id: 2, name: "David", age: 32 },
    { id: 3, name: "Emily", age: 24 }
];

function deleteUser(id) {
    const index = users.findIndex(user => user.id === id);
    if (index === -1) return false;

    users.splice(index, 1);
    return true;
}

console.log("Before delete:", users.length, "users");
deleteUser(1);
console.log("After delete:", users.length, "users");
console.log(users);

Generating Unique IDs

What this code does: Uses crypto.randomUUID() to create globally unique IDs instead of a simple counter.

function createUser(data) {
    return {
        id: crypto.randomUUID(),
        ...data
    };
}

const user1 = createUser({ name: "Michael" });
const user2 = createUser({ name: "David" });

console.log("User 1 ID:", user1.id);
console.log("User 2 ID:", user2.id);
console.log("IDs are unique:", user1.id !== user2.id);

Validating Data Before Creating

What this code does: Checks that a valid name is provided before creating a user. Throws a clear error if validation fails.

function createUser(data) {
    if (!data.name || typeof data.name !== "string") {
        throw new Error("A valid name is required");
    }
    return {
        id: crypto.randomUUID(),
        ...data
    };
}

try {
    createUser({ age: 30 });          // missing name
} catch (error) {
    console.log("Validation error:", error.message);
}

const validUser = createUser({ name: "Michael", age: 30 });
console.log("Successfully created:", validUser);

Filtering and Querying Records

What this code does: Accepts any condition function and returns all matching records — similar to a SQL WHERE clause.

let users = [
    { id: 1, name: "Michael", age: 28 },
    { id: 2, name: "David", age: 35 },
    { id: 3, name: "Emily", age: 22 }
];

function findUsersWhere(predicate) {
    return users.filter(predicate);
}

const adultsOver25 = findUsersWhere(user => user.age > 25);
console.log("Users older than 25:", adultsOver25);

const youngUsers = findUsersWhere(user => user.age < 25);
console.log("Users under 25:", youngUsers);

Practice: Complete Mini CRUD App

What this code does: Combines create, read, update, and delete into one working example with validation.

let users = [];

function createUser(data) {
    if (!data.name || typeof data.name !== "string") {
        throw new Error("A valid name is required");
    }
    const user = { id: crypto.randomUUID(), ...data };
    users.push(user);
    return user;
}

function findUserById(id) {
    return users.find(user => user.id === id);
}

function updateUser(id, updates) {
    const user = findUserById(id);
    if (!user) return null;
    Object.assign(user, updates);
    return user;
}

function deleteUser(id) {
    const index = users.findIndex(user => user.id === id);
    if (index === -1) return false;
    users.splice(index, 1);
    return true;
}

// Demo
const michael = createUser({ name: "Michael", age: 28 });
console.log("Created:", michael);

updateUser(michael.id, { age: 29 });
console.log("Updated:", findUserById(michael.id));

deleteUser(michael.id);
console.log("Remaining users:", users.length);

Quick Summary

  • CREATE → push() a new object with a unique ID
  • READ → find() for one record, return the whole array for all
  • UPDATE → find the record and use Object.assign()
  • DELETE → find the index and use splice()
  • Always validate data and handle “not found” cases cleanly
Tip: These same four operations appear in every real database — IndexedDB, SQLite, MongoDB, PostgreSQL. Master them here and the concepts transfer everywhere.

🧪 Test Your JavaScript Code

Edit the code on the left and click "Run Code" to see the console output.

📝 JavaScript Code
👁 Console Output

Click "Run Code" to see the output here.

Ctrl + Enter to run   Esc to close