First post in a series showing how to accomplish the same task in JS and Scala.

Here we will show a little functional style programming using closures.

Task: write a function that takes an Int as an argument, and returns a function. The returned function also takes an Int as an argument and returns the sum of the two ints

// JavaScript
function add(num1) {
  return function(num2) {
    return num1 + num2;
  };
}

var x = add(4);
x(5);
//=> 9

Now with Scala:

// Scala
def add(num: Int) = (num2: Int) => num + num2

val x = add(4)
x(5)
//=> Int = 9

// using double invocation:
add(4)(5)
//=> Int = 9

We can closely approximate the Scala Syntax using JavaScript’s arrow functions from the ES6 version of the language:

// JavaScript
const addWithES6 = (num) => (num2) => num + num2;

addWithES6(4)(5)
//=>9