Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
All about Functions and Scopes in JavaScript
Next article icon

All about Functions and Scopes in JavaScript

Last Updated : 21 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 function declarations.
  • 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 Functions.

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
<script type="text/javascript" charset="utf-8">     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     console.log(add(2, 3)); </script> 

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:

HTML
<script type="text/javascript" charset="utf-8">     // 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 </script> 

Output:

5  1

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 the JavaScript | Callbacks article for more details.

Example:

JavaScript
<script type="text/javascript" charset="utf-8">     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);       </script> 

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().

Arrow function: It is an expression or syntax which is  simplified as well as a more compact version of a regular or normal function expression or syntax. It is easier to implement than a normal function but has some limitations. Please refer to ES6 Arrow Function to learn more about arrow functions

Syntax:

  • For Single Argument:
let function_name = argument1 => expression
  • For Multiple Arguments:
let function_name = (argument1, argument2 , ...) => expression

Example:

HTML
<script>            //  Normal function for multiplication     // of two numbers     function multiply(a, b) {         return a * b;     }     console.log(multiply(3, 5)); </script> 

Output:

15


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 an 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
<script type="text/javascript" charset="utf-8">     const name = "GeeksforGeeks";          function introduceMyself(greet) {     const audience = "Everyone";     function introduce() {       console.log(`${greet} ${audience}, This is ${name} Learning!`);     }     introduce();     }          introduceMyself("Hello"); </script> 

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 search 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
<script type="text/javascript" charset="utf-8">     const name = "GeeksforGeeks";          function introduceMyself(greet) {       const audience = "Everyone";            function introduce() {         console.log(`${greet} ${audience}, This is ${name} Learning`);       }            introduce();     }          introduceMyself("Hello"); </script> 

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
<script type="text/javascript" charset="utf-8">     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 </script> 

Output:

Souvik  Private  Abhijit  Private

Example 2:

JavaScript
<script type="text/javascript" charset="utf-8">     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 </script> 

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 a lexical environment. Please refer to the Closure in JavaScript article to understand this concept.

Example:

JavaScript
<script type="text/javascript" charset="utf-8">     function closureDemo(){         const  a = 3;                  return function (){               console.log(a);           }     }          // Returns the definition of inner function     const innerFunction = closureDemo();     innerFunction(); // 3 </script> 

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 a 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
<script type="text/javascript" charset="utf-8">     // 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();  </script> 

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!

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.and 


Next Article
All about Functions and Scopes in JavaScript

S

sjsouvik
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Blogathon
  • Blogathon-2021
  • javascript-functions

Similar Reads

    Array of functions in JavaScript
    Given an array containing functions and the task is to access its element in different ways using JavaScript. Approach: Declare an array of functions.The array of functions works with indexes like an array function. Example 1: In this example, the function call is initiated from the element of the a
    2 min read
    Are functions objects in javascript?
    Yes, Functions are considered first-class objects, which means they have the same capabilities as other objects. The following are examples that demonstrates functions behaving as objects:Can be assigned to variableJavaScript// Assign a function to a variable const x = function() { return `GfG!`; };
    1 min read
    Function that can be called only once in JavaScript
    In JavaScript, you can create a function that can be called only once by using a closure to keep track of whether the function has been called before. JavaScript closure is a feature that allows inner functions to access the outer scope of a function. Closure helps in binding a function to its outer
    3 min read
    JavaScript Course Functions in JavaScript
    Javascript functions are code blocks that are mainly used to perform a particular function. We can execute a function as many times as we want by calling it(invoking it). Function Structure: To create a function, we use function() declaration. // Anonymous function function(){ // function...body } /
    4 min read
    Interesting Facts about JavaScript Functions
    Let us talk about some interesting facts about JavaScript Functions that can make you an efficient programmer.Functions Are First-Class CitizensJavaScript treats functions as first-class citizens, meaning they can be:Stored in variablesPassed as arguments to other functionsReturned from other functi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences