Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
the fibonnaci sequance javascript

I am working on a function that shows the value of a given number in the Fibonacci sequence. However, it seems the last number is not quite correct on following the Fibonacci algorithm. Any clues on what I am doing wrong here?

const fibonacci = function(num) {
    let fsec=[];
    fsec[0]= 0;
    fsec[1]= 1;
    
    for(let i=2; i<=num; i++){
        fsec[i]=fsec[i-2]+fsec[i-1];
        fsec.push(i)
    }

    return fsec[fsec.length-1]
};

fibonacci(6)
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

2 things in your for loop. i should be less than num and the push should push the number, not the iterator.

Change to this:

for(let i=2; i<num; i++){
 fsec[i]=fsec[i-2]+fsec[i-1];
 fsec.push(fsec[i])
}
about 4 years ago · Juan Pablo Isaza Report

0

use below code:

const fibonacci = function(num) {
  let fsec=[];
  fsec[0]= 0;
  fsec[1]= 1;
        
  for(let i=2; i<num; i++){
    fsec.push(fsec[i-2]+fsec[i-1])
  }
        
  // console.log(fsec)
  // console.log(fsec[fsec.length-1])
  return fsec[fsec.length-1]                
};

fibonacci(6)
about 4 years ago · Juan Pablo Isaza Report

0

The fsec.push(i) is unnecessary and is the problem in this case..

const fibonacci = function(num) {
        let fsec=[];
        fsec[0]= 0;
        fsec[1]= 1;
        
        for(let i = 2; i <= num; i++){
            fsec[i] = fsec[i-2] + fsec[i-1];
        }
        
        return fsec[fsec.length - 1]
};

console.log(fibonacci(6));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!