function fibonacciDP(n) {
// Validate input
if (typeof n !== 'number' || !Number.isInteger(n) || n < 0) {
return NaN; // Handle invalid input
}
// Base cases
if (n === 0) return 0;
if (n === 1) return 1;
// Create an array to store Fibonacci numbers up to n
const fibArray = new Array(n + 1);
fibArray[0] = 0; // F(0)
fibArray[1] = 1; // F(1)
// Fill the array using the previous two values
for (let i = 2; i <= n; i++) {
fibArray[i] = fibArray[i - 1] + fibArray[i - 2];
}
return fibArray[n]; // Return the nth Fibonacci number
}
It is classic example of dynamic programming. you can follow below link for better understanding, https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/