---
id: 7a97b79c096ecb000d03bd36
title: Build an Nth Fibonacci Number Calculator
challengeType: 26
dashedName: build-an-nth-fibonacci-number-calculator
---

# --description--

**Objective:** Fulfill the user stories below and get all the tests to pass to complete the lab.

**User Stories:**

1. You should create a function named `fibonacci`.
2. You should define an array named `sequence` within the `fibonacci` function, and it should be initialized with the values `[0, 1]`.
3. The `fibonacci` function should accept one parameter, a non-negative integer `n`.
4. Calling `fibonacci(n)` should use a dynamic programming approach to compute and return the `n`-th number from the Fibonacci sequence, where each number is the sum of the two preceding numbers.
5. Each computed Fibonacci number should be appended to the `sequence` array.

# --hints--

You should have a function named `fibonacci`.

```js
assert.isFunction(fibonacci);
```

Your `fibonacci` function should take a single parameter.

```js
const params = __helpers.getFunctionParams(fibonacci.toString());
assert.equal(params.length, 1);
```

You should have an array named `sequence` within the `fibonacci` function initialized to `[0, 1]`.

```js
assert.match(__helpers.removeJSComments(fibonacci.toString()), /(const|let|var)\s+sequence\s*=\s*\[\s*0\s*,\s*1\s*\]/);
```

`fibonacci(0)` should return `0`.

```js
assert.equal(fibonacci(0), 0);
```

`fibonacci(1)` should return `1`.

```js
assert.equal(fibonacci(1), 1);
```

`fibonacci(2)` should return `1`.

```js
assert.equal(fibonacci(2), 1);
```

`fibonacci(3)` should return `2`.

```js
assert.equal(fibonacci(3), 2);
```

`fibonacci(5)` should return `5`.

```js
assert.equal(fibonacci(5), 5);
```

`fibonacci(10)` should return `55`.

```js
assert.equal(fibonacci(10), 55);
```

`fibonacci(15)` should return `610`.

```js
assert.equal(fibonacci(15), 610);
```

You should not use recursion in your code.

```js
const funcStr = __helpers.removeJSComments(fibonacci.toString());
const bodyMatch = funcStr.match(/^[^{]*\{([\s\S]*)\}[^}]*$/) || funcStr.match(/=>\s*([\s\S]+)$/);
assert(bodyMatch && !bodyMatch[1].match(/\bfibonacci\s*\(/));
```

# --seed--

## --seed-contents--

```js

```

# --solutions--

```js
function fibonacci(n) {
  const sequence = [0, 1];

  if (n < 2) {
    return sequence[n];
  }

  for (let i = 2; i <= n; i++) {
    sequence.push(sequence[i - 1] + sequence[i - 2]);
  }

  return sequence[n];
}
```
