Published on

The return of values

Authors

Consider these two different blocks of code that log the same value on line number 9:

let result = null

function sum(x, y) {
  result = x + y
}

sum(1, 2)

console.log(result)
function sum(x, y) {
  return x + y
}

let result = sum(1, 2)

console.log(result)

Note the difference between the two function definitions on line 4.

On line 7 in the left code block (or the top code block if you're reading on a narrower display), calling the function sum with two arguments 1 and 2 returns nothing, but it has the effect of setting the result variable declared in the outer block to the value of the evaluated expression 1 + 2. Furthermore, the statement result = x + y inside the function body expects the result variable to be declared outside the scope of the function body.

Now let's examine the right (or the bottom) code block. On line 7, calling the function sum with two arguments 1 and 2 returns the value of the evaluated expression 1 + 2 which is then assigned to the result variable.

Though both code blocks log the same value in the console on line 9, the code block on the right (or bottom) is more functional than the left (or top). The two obvious reasons that make it more functional are the facts that it returns a value and the fact that the output just depends on the input arguments of the function.