Implementing the Fibonacci Sequence in JavaScript: Common Approaches and Variations
As a developer, you’ve likely encountered the task of writing a function to calculate values in the Fibonacci sequence. This classic problem often appears in coding interviews, typically asking for a recursive implementation. However, interviewers may sometimes request specific approaches. In this article, we’ll explore the most common Fibonacci sequence implementations in JavaScript.
What is the Fibonacci Sequence?
First, let’s refresh our memory. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. It starts with 0 and 1:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …
Common Implementation Approaches
1. Recursive Approach
The most traditional request is for a recursive implementation:
function fibonacciRecursive(n) { if (n < 1) { return 0; } if (n === 1) { return 1; } return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2); }
While straightforward, this approach isn’t performant for large values of n. On a MacBook Pro i9 with 16 GB RAM, calculating the 40th Fibonacci number took about 1.5 seconds:
console.time('Recursive'); fibonacciRecursive(40); console.timeEnd('Recursive'); VM379:3 Recursive: 1521.569091796875 ms
Attempting to calculate the 50th number caused the Chrome tab to become unresponsive.
2. Recursive Approach with Caching (Memoization)
The next variation of this question is to improve performance by adding a caching mechanism to our recursive implementation:
function fibonacciCached(n, cached = {[0]: 0, [1]: 1}) { if (n < 1) { return 0; } if (n === 1) { return 1; } if (cached[n]) { return cached[n]; } cached[n] = fibonacciCached(n - 1, cached) + fibonacciCached(n - 2, cached); return cached[n]; }
This approach introduces a cached object with initial values for 0 and 1. For any given number, we first check if we've already calculated its Fibonacci value. If so, we return the cached result instead of recalculating it. Otherwise, we calculate that value and store it in cached.
The performance improvement is significant (due to the additional memory used, of course). Calculating the 40th Fibonacci number took ~0.02 ms:
console.time('Recursive, with caching'); fibonacciCached(40); console.timeEnd('Recursive, with caching'); VM382:3 Recursive, with caching: 0.01806640625 ms
3. Iterative Approach with a for Loop
Another common variation is implementing the Fibonacci sequence using a for loop:
function fibonacciWithIteration(n) { if (n <= 0) { return 0; } if (n === 1) { return 1; } let prev = 0; let next = 1; let result = 1; for (let i = 2; i <= n; i++) { result = prev + next; [prev, next] = [next, prev + next]; } return result; }
This approach is much faster than the basic recursive method (the one without caching):
console.time('With iteration'); fibonacciWithIteration(40); console.timeEnd('With iteration'); VM44:22 With iteration: 0.10107421875 ms
The iterative approach can handle very large input values efficiently:
console.time('With iteration'); const result = fibonacciWithIteration(1400); console.log(result); console.timeEnd('With iteration'); VM325:22 1.7108476902340223e+292 VM325:23 With iteration: 0.5830078125 ms
Bonus: Returning the Fibonacci Sequence as an Array
Interviewers might also ask you to return the entire Fibonacci sequence up to the n-th number as an array. Let’s implement this using both recursive and iterative approaches.
Recursive approach
function fibonacciSequence(n) { if (n === 0) { return [0]; } if (n === 1) { return [0, 1]; } const arr = fibonacciSequence(n - 1); const currentValue = arr[n - 1] + arr[n - 2]; return [...arr, currentValue]; } console.log(fibonacciSequence(5)); // [0, 1, 1, 2, 3, 5]
This function works as follows:
- For 0 and 1, we return hardcoded arrays.
- For other cases:
- We get the sequence for the previous number and store it in arr.
- We calculate currentValue by summing the last two values of arr.
- We combine arr and currentValue in a new array and return it.
Iterative Approach
function fibonacciSequenceWithIteration(n) { if (n < 1) { return [0]; } let prev = 0; let next = 1; const arr = [prev, next]; for (let i = 2; i <= n; i++) { arr.push(prev + next); [prev, next] = [next, prev + next]; } return arr; } console.log(fibonacciSequenceWithIteration(5)); // [0, 1, 1, 2, 3, 5]
This function works as follows:
- If the input is 0, we return an array with only the element 0.
- For other cases:
- We initialize prev and next variables to store the previous and next values.
- We create arr with initial values [0, 1].
- We iterate from 2 to n, pushing the sum of prev and next to arr in each iteration.
- We update prev and next values and continue to the next iteration.
Conclusion
While this article covers several common Fibonacci sequence implementations, it’s not an exhaustive list. If you’ve encountered other variations in interviews or your work, please share them in the comments!
Stay updated with the latest JavaScript and software development news! Join my Telegram channel for more insights and discussions: TechSavvy: Frontend & Backend.
以上是Implementing the Fibonacci Sequence in JavaScript: Common Approaches and Variations的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

禅工作室 13.0.1
功能强大的PHP集成开发环境

SublimeText3汉化版
中文版,非常好用

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中