-3

How does JavaScript 'store' the s variable as an array? why wouldn't the s variable will be overwritten in this line"s.push(s[s.length - 1] + s[s.length - 2]); "

var number = prompt("fibonacci")

var fibo = function(n) {
  if (n === 1) {
    return [0, 1];
  } else {
    var s = fibo(n - 1);
    s.push(s[s.length - 1] + s[s.length - 2]);
    return s;
  }
}
console.log(fibo(number));

BUT HOW IS IT STORING THE VARIABLE AS AN ARRAY?

Vanojx1
  • 5,574
  • 2
  • 23
  • 37
joseMana
  • 23
  • 1
  • 7
  • Read about [push method](https://www.w3schools.com/jsref/jsref_push.asp) , it ADDS to an array, so s.push() is just adding, never removing. – Foo Bar Jun 13 '17 at 12:09
  • Just because it's an easier way to calculate Fibonacci value. Check Array behaviour: https://www.w3schools.com/jsref/jsref_push.asp – FieryCat Jun 13 '17 at 12:10
  • `push` appends a value to `s` array; this value is evaluated before `push` executes. So, it changes `s`, but it doesn't overwrite it, it just extends it. – Egor Stambakio Jun 13 '17 at 12:10
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=example – epascarello Jun 13 '17 at 12:10
  • Possible duplicate of [Fibonacci Sequence (JS) - Sum of Even Numbers](https://stackoverflow.com/questions/32085932/fibonacci-sequence-js-sum-of-even-numbers) – prasanth Jun 13 '17 at 12:16
  • 1
    This is a beginner programming problem, not a problem with understanding Fibonacci... – Christophe Roussy Jun 13 '17 at 12:18

2 Answers2

1
return [0, 1]; // Creates the array
...
var s = fibo(n - 1); // Assigns array to s (s references array)

s.push(s[s.length - 1] + s[s.length - 2]);

only push writes to the array (left hand side)

other operations on the same line only read from it (right hand side)

I recommend you start with the basics and later start with recursive functions.

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
0

Push doesn't overwrite the array, rather just adding the new item to the end of it.

var s = [0, 1];

var lastItem = s[s.length - 1]; // 1
var itemBeforeLast = s[s.length - 2]; // 0
var sum = lastItem + itemBeforeLast; // 1

s.push(sum); // s is now [0, 1, 1]
JuhG
  • 140
  • 10