If you’re given an integer n, how do you print the Fibonacci sequence up to n in JavaScript?

First of all, since there are varying understanding of Fibonacci sequence, in this case we’ll assume that the 0th number is 0, 1st number is 1 and the next numbers are the sum of the previous 2 numbers.

For example, if the n is 10, we’ll print form 0th number to 10th number, resulting in [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].

## Solution

```
function printFibonacci(n) {
let sequence = [];
for (let i = 0; i <= n; i ++) {
if (i == 0) sequence.push(0);
else if (i == 1) sequence.push(1);
else {
sequence.push(sequence[sequence.length-1] + sequence[sequence.length-2]);
}
}
return sequence;
}
console.log(printFibonacci(10)); //[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
```

With this code, we’re essentially iterating from 0 to n adding 0 and 1 as 0th and 1st number respectively. Then for the next numbers, we’ll be taking the sum of the last 2 numbers and repeating it until we reach the nth number.

Time Complexity : O(n)

We are iterating n times so are complexity matches our number of inputs.

Space Complexity : O(n)

We’re using an array to store our answer and the array grows accordingly to n.

## Conclusion

That’s how you can print a sequence of Fibonacci numbers. Quite simple, right?

You’re essentially printing numbers by summing up the last 2 numbers.

For a similar tutorial about Fibonacci numbers, you can check out my post on How To Get nth Fibonacci Number in JavaScript?

For you who want to brush up your JavaScript skills, whether to deepen or learn form zero, I recommend you try Codecademy. There are tons of JavaScript lessons that you can learn in a structured and interactive way. You can learn from the most basic materials to advanced stuffs and even preparing for technical interviews. Go try it now!

If you have a better solution be it code-wise or efficiency-wise, please do comment below!

Check out the rest of my blog for more helpful contents on Data Structures and Algorithms in JavaScript!

See you next post!