Checking for Fibonacci numbers in JavaScript

JavascriptWeb DevelopmentObject Oriented ProgrammingFront End Technology

We are required to write a JavaScript function that takes in a number and checks whether it is a Fibonacci number or not (i.e., it falls in Fibonacci series or not).

Our function should return true if the number is a Fibonacci number, false otherwise.

The code for this will be −

const num = 2584;
const isFibonacci = num => {
   if(num === 0 || num === 1){
      return true;
   }
   let prev = 1;
   let count = 2;
   let temp = 0;
   while(count <= num){
      if(prev + count === num){
         return true;
      };
      temp = prev;
      prev = count;
      count += temp;
   };
   return false;
};
console.log(isFibonacci(num));
console.log(isFibonacci(6765));
console.log(isFibonacci(45));
console.log(isFibonacci(8767));

Following is the output on console −

true
true
false
false
raja
Published on 09-Oct-2020 11:30:57
Advertisements