This page looks best with JavaScript enabled

Change Function Scope in Javascript

 ·   ·  ☕ 2 min read

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 -

1
2
3
4
5
6
7
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.

1
2
3
4
5
6
7
8
9
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.

1
2
3
4
5
6
7
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.

1
2
3
4
5
(function (x, y) {
  var sum = x + y;
  console.log("sum function: ", sum);
  return sum;
})(2, 3);
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things