Change Function Scope in Javascript

Javascript has lexical scope - the variable values are available and valid based on their position. The same is applicable to functions.

At the same time declarations are brought to the top of their block at compile time. In other words, they are hoisted at the time of compilation, and hence variables and functions are available to statements accessing them before the actual declaration.

Consider the following function -

getSum(2, 3);

function getSum(x, y) {
  var sum = x + y;
  console.log("sum function: ", sum); // 5
  return sum;
}

Even though the function is declared after the actual call, the above piece of code works without issues.

However, this might be an issue if you need functions to not have global scope, i.e., function should exist only at certain times in the code.

This can be achieved using one of the following options -

Use named functions

The below code will throw an error since getSum is not available at the time of being called.

getSum(2, 3); // TypeError: getSum is not a function

var getSum = function(x, y) {
  var sum = x + y;
  console.log("sum function: ", sum);
  return sum;
};

// getSum(2, 3); // this works
Use the more modern notation

Use arrow functions for better readability.

getSum(2, 3); // TypeError: getSum is not a function

var getSum = (x, y) => {
  sum = x + y;
  console.log("sum function: ", sum);
  return sum;
};

Or, go extreme and have a function without its properties :)

Use IIFE

Use ‘immediately invoked function expression’ if you don’t really find it necessary to have reusable function.

(function(x, y) {
  var sum = x + y;
  console.log("sum function: ", sum);
  return sum;
})(2, 3);
comments powered by Disqus