Generate Fibonacci Sequence - JavaScript | Hackerank

Author: neptune | 07th-Apr-2023

Problem Statement:

Write a JavaScript function fibonacciSequence() to generate a FIbonacci sequence. 

Example 1

fibonacciSequence(5); 

It should return an array of the fibonacci sequence numbers "0, 1, 1, 2, 3, 5". 


Example 2

fibonacciSequence(6); 

It should return an array of the fibonacci sequence numbers "0, 1, 1, 2, 3, 5, 8". 


Note: 5 is the array index which return the 6 values form the starting of the array. Solution:


Solution: 

This function takes a number n as input and returns an array of the first n+1 numbers in the Fibonacci sequence.


function fibonacciSequence(input) {

    //Type your code here.

    let sequence = [0,1];

    let i=2;

    while(i<=input){

        sequence[i] = sequence[i-1]+sequence[i-2]

        i++;

        // console.log(sequence);

    }

    return sequence

}



Execution: