Fibonacci series in JavaScript
Print the first n Fibonacci numbers. Press Run to try it, then change the code and run it again.
main.js
function fibonacci(n) {
const series = [0, 1];
while (series.length < n) {
series.push(series.at(-1) + series.at(-2));
}
return series.slice(0, n);
}
console.log(fibonacci(10).join(", "));
Output
Press Run to see the output.
More JavaScript examples
- Hello, World · Print a line of text to the console.
- Reverse a string · Split a string into characters, reverse them and join them back.
- Check a prime number · Test divisors up to the square root of the number.
- Promises with async/await · Wait for a timer with await, the way you would wait for a network request.
- map, filter and reduce · Transform, filter and total an array of objects.