# Week 2

Backends can't run top-to-bottom. Database queries take time. File reads take time. Network calls take time. If your server waited for each operation to complete before doing anything else, it could only serve one request at a time.

This week you'll learn how JavaScript handles operations that take time. You'll understand callbacks, build your own higher-order functions, and see why delayed execution is essential for backends.

## Contents

* [Preparation](/course-content/backend/advanced-javascript/week2/preparation.md)
* [Slides](https://github.com/HackYourFuture-CPH/program/blob/main/courses/backend/advanced-javascript/week2/session-materials/slides/index.html)
* [Session Plan](/course-content/backend/advanced-javascript/week2/session-plan.md) (for mentors)
* [Session Materials](https://github.com/HackYourFuture-CPH/program/blob/main/courses/backend/advanced-javascript/week2/session-materials/README.md)
* [Assignment](/course-content/backend/advanced-javascript/week2/assignment.md)

## Learning Goals

By the end of this session, you will be able to:

* [ ] Assign functions to variables and pass them as arguments
* [ ] Return functions from other functions (function factories)
* [ ] Use `reduce()` to aggregate data (totals, grouping)
* [ ] Write and use callback functions
* [ ] Understand how delayed callbacks work
* [ ] Use `setTimeout()` to schedule delayed execution
* [ ] Use Node.js `fs.readFile()` with callbacks
* [ ] Understand the error-first callback pattern

### After this session you will understand code like this

```js
// Example: Simulated database lookup
function findTeaById(id, callback) {
  setTimeout(() => {
    const tea = teas.find((t) => t.id === id);
    callback(tea);
  }, 500);
}

findTeaById(3, (tea) => {
  console.log("Found:", tea.name);
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://program.hackyourfuture.dk/course-content/backend/advanced-javascript/week2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
