Rocket Squirrel Rocket Squirrel
Rocket Squirrel

A global community of coders, developers, and designers

May 2023


Project Euler with ES6 – Problem 2


My article on Problem 1 is here.

This is Project Euler’s Problem 2:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

To solve this I’ll dispense with the unnecessary generator and spread operator I shoehorned into the solution of the previous problem and just use a while loop:

// Previous term, current term, and running total
let [prev, cur, sum] = [0, 1, 0];

while (cur < 4000000) {
    if (cur % 2 == 0) { // Even terms only
        sum += cur; // Add to running total
    [prev, cur] = [cur, prev + cur]; // Calculate next term in sequence

console.log(sum); // 4613732

The ES6 feature I’m highlighting in this article is Destructuring Assignment. It provides a way to assign to multiple variables at once. The first place I use it is at the top:

let [prev, cur, sum] = [0, 1, 0];

Here prev is set to 0, cur is set to 1, and sum is set to 0, which is underwhelming. The interesting line is at the end of the while loop:

[prev, cur] = [cur, prev + cur]; // Calculate next term in sequence

Here prev is set to cur and cur is set to prev + cur. But wait, is the value of prev in prev + cur the one from before or after the assignment? It’s the one from before. In ES5 it’s necessary to have an explicit temporary variable:

var tmp = cur;
cur += prev;
prev = tmp;

In ES6 the temporary variable can be hidden away under the hood.

All code was tested on Node v8.1.4.

Comments 0
There are currently no comments.