# Read the Results Back

*Task 4 of 6 · [Data In, Data Out](https://gpu.rocks/learn/data-in-data-out-42b68d01.md) · GPU.js Learn*

A kernel's return value doesn't stay on the GPU — awaiting the call hands you the
finished result as an ordinary (typed) array. From there it's plain JavaScript: loop over it,
sum it, feed it to a chart, whatever you like.

This round trip is the heartbeat of GPGPU: **upload → compute in parallel →
read back**. Here the parallel part computes 128 squares; the read-back part totals them.

## Goal

**Goal:** make the kernel return `x²` for each thread, then sum
the returned array in plain JavaScript and log the total with `console.log`.

## Requirements

- Kernel returns `this.thread.x * this.thread.x` for all 128 threads
- Sum the returned `result` array in ordinary JavaScript — outside the kernel
- Log the total (it should come to `690880`)

## Hint 1 — what comes back?

With `output: [128]`, `await squares()` gives you a
`Float32Array` of 128 numbers. It's indexable and loopable like any array.

## Hint 2 — the sum

A plain `for` loop after the kernel call:

```js
let total = 0;
for (let i = 0; i < result.length; i++) {
  total += result[i];
}
```

## Same idea elsewhere

Read-back is never free: CUDA's `cudaMemcpy` device→host and WebGPU's
`mapAsync` staging buffers exist for exactly this step — and minimizing round trips
is rule one of real GPU performance (**Pipelines & Textures** makes a whole
meal of it).

## Starter code

```js
// Kernel output comes back to JavaScript as a typed array.
const gpu = new GPU({ mode });

const squares = gpu.createKernel(function () {
  // TODO: return this thread's index, squared
  return this.thread.x;
}, { output: [128] });

const result = await squares();
console.log(result);

// TODO: total up `result` in plain JavaScript, then:
// console.log('sum of squares:', total);
```

---

Interactive version: https://gpu.rocks/learn/data-in-data-out-42b68d01/4

[Previous task](https://gpu.rocks/learn/data-in-data-out-42b68d01/3.md) · [Next task](https://gpu.rocks/learn/data-in-data-out-42b68d01/5.md)
