Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

All about Functions and Scopes in JavaScript

  • Difficulty Level : Easy
  • Last Updated : 19 Sep, 2021

In this article, we will cover all the basic concepts of JS functions, callbacks, scopes, closures in-depth which would help you to –

  • understand different types of functions declaration.
  • make better use of functions.
  • understand how different scopes and scope chain works in JS.
  • learn about closures and how to use them.

We will understand all these concepts through the examples & also understand their implementations. Let’s begin the discussion with Javascript Function.

Functions: Function allows us to declare & pack a bunch of code in a block so that we can use (and reuse) a block of code in our programs. Sometimes, they take some values as `parameters` to do the operation and return some value as a result of the operation.

 

Example:

Javascript




function add(a, b) {
   
    // a and b are the parameters of this
    // function code to do the operation
    return a + b; // return statement
}
  
// Invoking the function and 2, 3
// are arguments here
add(2, 3);

Output: 

5

First-Class Citizen: If any programming language has the ability to treat functions as values, to pass them as arguments and to return a function from another function then it is said that programming language has First Class Functions and the functions are called First-Class Citizens in that programming language. Functions will be considered as First-Class Citizen in JavaScript if the functions:

  • store functions in a variable.
  • pass a function as an argument to another function.
  • return a function from another function.

Function Expressions: When a function is stored inside a variable, it is called a function expression. This can be named or anonymous. If a function doesn’t have any name and is stored in a variable, then it would be known as an anonymous function expression. Otherwise, it would be known as a named function expression. Please refer to the JavaScript Function expression article for more details.

Example:

Javascript




// Anonymous function expression
const add = function (a, b){
    return a + b;
}
  
// Named function expression
const subtractResult = function subtract(a, b){
    return a - b;
}
  
console.log(add(3, 2)); // 5
console.log(subtractResult(3, 2)); // 1

The output will be 5 & 1 respectively.



Callbacks: Storing a function in a variable makes it really easy to pass a function to another function as an argument. A function that takes other functions as arguments or returns a function is known as a higher-order function. A function that is passed as an argument into another function is known as a callback function. In simple words, If we want to execute a function right after the return of some other function, then callbacks can be used. Please refer to theavaScript | Callbacks article for more details.

Example:

Javascript




function showLength(name, callback) {
  callback(name);
}
  
// function expression `nameLength`
const nameLength = function (name) {
  console.log(`Given Name ${name} which 
  is ${name.length} chars long`);
};
  
// Passing `nameLength` as a callback function
showLength("GeeksforGeek", nameLength); 

Output:

Given Name GeeksforGeek which is 12 characters long

Template Literal in ES6 provides new features to create a string that gives more control over dynamic strings. Traditionally, String is created using single quotes (‘) or double quotes (“) quotes. Template literal is created using the backtick (`) character that allows declaring the embedded expressions. Generally, we use callback function in array methods – forEach(), map(), filter(), reduce().

Scope: It is a region of the program where a variable can be accessed. In other words, scope determines the accessibility/visibility of a variable. Since JavaScript looks like a C-family language, it is very obvious to think that scoping in JavaScript is similar to that in most of the back-end programming languages like C, C++ or Java. Please refer to the What is Variable Scope in JavaScript? article for more details. There’re 3 kinds of scopes in JavaScript:

  • Global scope: Variables declared outside of all functions are known as global variables and in the global scope. Global variables are accessible anywhere in the program.
  • Function scope: Variables that are declared inside a function are called local variables and in the function scope. Local variables are accessible anywhere inside the function.  
  • Block scope: Variable that is declared inside a specific block & can’t be accessed outside of that block. In order to access the variables of that specific block, we need to create object for it.

The code inside a function has access to:

  • the function’s arguments.
  • local variables declared inside the function.
  • variables declared in its parent function’s scope.
  • global variables.

Javascript




const name = "GeeksforGeeks";
  
function introduceMyself(greet) {
  const audience = "Everyone";
  function introduce() {
    console.log(`${greet} ${audience}, This is ${name} Learning!`);
  }
  introduce();
}
  
introduceMyself("Hello");

Output:

Hello Everyone, This is GeeksforGeeks Learning!

Block scope: This tells us that any variable declared inside a block ({}) can be accessed only inside that block.  



Now, what is a block? a block {} is used to group JavaScript statements together into 1 group so that it can be used anywhere in the program where only 1 statement is expected to be written.

Block scope is related to variables declared with `let` and `const` only. Variables declared with `var` do not have block scope.

Example:

{
    let a = 3;
    var b = 2;
}

console.log(a); //Uncaught ReferenceError: a is not defined
console.log(b); // 2 as variables declared with `var` is  
functionally and globally scoped NOT block scoped

 

Scope chain: Whenever our code tries to access a variable during the function call, it starts the searching from local variables. And if the variable is not found, it’ll continue searching in its outer scope or parent functions’ scope until it reaches the global scope and completes searching for the variable there. Searching for any variable happens along the scope chain or in different scopes until we get the variable. If the variable is not found in the global scope as well, a reference error is thrown.  

Example:

Javascript




const name = "GeeksforGeeks";
  
function introduceMyself(greet) {
  const audience = "Everyone";
  
  function introduce() {
    console.log(`${greet} ${audience}, This is ${name} Learning`);
  }
  
  introduce();
}
  
introduceMyself("Hello");

Output:

Hello Everyone, This is GeeksforGeeks Learning

In the above example, when the code attempts to access variable `name` inside the `introduce()` function, it didn’t get the variable there and tried to search in its parent function’s (`introduceMyself()`) scope. And as it was not there, it finally went up to global scope to access the variable and got the value of the variable `name`.

Variable shadowing: If we declare a variable with the same name as another variable in the scope chain, the variable with local scope will shadow the variable at the outer scope. This is known as variable shadowing. Please refer to the Variable Shadowing in JavaScript article for further details.



Example 1:

Javascript




let name = "Abhijit";
var sector = "Government";
  
{
  let name = "Souvik";
    
  // as `var` is NOT block scoped(globally s
  // coped here), it'll update the value
  var sector = "Private"
  console.log(name); //Souvik
  console.log(sector); //Private
}
  
console.log(name); //Abhijit
console.log(sector); //Private

Output:

Souvik
Private
Abhijit
Private

Example 2:

Javascript




let name = "Abhijit";
var sector = "Government";
  
function showDetails() {
  let name = "Souvik";
  
  // `var` is functionally scoped here,
  // so it'll create new reference with 
  // the given value for organization
  var sector = "Private";
  console.log(name); // Souvik
  console.log(sector); // Private
}
  
showDetails();
console.log(name); // Abhijit
console.log(sector); // Government

Explanation: In the case of example 1, the `name` variable is shadowing the variable with the same name at the outer scope inside the block as we have used `let` to declare the variable. But, the `sector` variable is also updating the value at the same time as we have used `var` to declare it. And as we know `var` is functionally and globally scoped, the declaration with the same name(`sector`) inside the block will update the value at the same reference. Whereas in the case of example 2, the `sector` variable inside the function is function scoped and will create a new reference which will just shadow the variable with the same name declared outside.

Output:

Souvik
Private
Abhijit
Government

Closure: It is an ability of a function to remember the variables and functions that are declared in its outer scope.

MDN defines closure as -“The combination of a function bundled together with references to its surrounding state or the lexical environment

Now, if you’re thinking, what’s the lexical environment? function’s local environment along with its parent function’s environment forms lexical environment. Please refer to the Closure in JavaScript article to understand this concept.



Example:

Javascript




function closureDemo(){
    const  a = 3;
      
    return function (){
          console.log(a);  
    }
}
  
// Returns the definition of inner function
const innerFunction = closureDemo();
innerFunction(); // 3

The output will be 3.

In the above example, when the `closureDemo()` function is called, it’ll return the inner function along with its lexical scope. Then when we attempt to execute the returned function, it’ll try to log the value of `a` and get the value from its lexical scope’s reference. This is called closure. Even after the outer function’s execution, the returned function still holds the reference of the lexical scope.

Advantages:

  • Currying
  • Memoization
  • Module design pattern

Disadvantages:

  • Overconsumption of memory might lead up to the memory leak as the innermost function holds the reference of the lexical scope and the variables declared in its lexical scope won’t be garbage collected even after the outer function has been executed.

Immediately-Invoked Function Expression(IIFE): An immediately-invoked function expression or IIFE is a function that’s called immediately once it’s defined. Please refer to the JavaScript | Immediately Invoked Function Expressions (IIFE) article for further details.

Syntax:

(function task(){
    console.log("Currently writing a blog on JS functions");
})();

We’re basically wrapping a function in parenthesis and then adding a pair of parenthesis at the end to invoke it.

  • Passing arguments into IIFE: We can also pass arguments into IIFE. The second pair of parenthesis not only can be used to invoke the function immediately but also can be used to pass any arguments into the IIFE. 
(function showName(name){
   console.log(`Given name is ${name}`); // Given name is Souvik
})("Souvik");
  • IIFE and private scope: If we can use IIFE along with closure, we can create a private scope and can protect some variables from being accessed externally. The same idea is used in module design patterns to keep variables private.  

Example:

Javascript




// Module pattern
let greet = (function () {
  const name = "GeekforGeeks"; // Private variable
  
  return {
    introduce: function () {
      console.log(`Hello, This is ${name} Learning!`);
    },
  };
})();
  
console.log(greet.name); //undefined
  
// Hello, This is GeekforGeeks Learning!
greet.introduce();

IIFE helps to prevent access to the `name` variable here. And the returned object’s `introduce()` method retains the scope of its parent function(due to closure), we got a public interface to interact with `name`.

Output:

undefined
Hello, This is GeekforGeeks Learning!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!