Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
What is a Constructor in JavaScript?
Next article icon

What is the practical use for a closure in JavaScript?

Last Updated : 14 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, closures are defined as inner functions that have access to variables and parameters of outer function even after the outer function has returned. The below examples show the practical use of closures:

Example: In this example, a variable mult is defined that is local to the function multFn and is only accessible inside this function. When an inner function is declared, JavaScript creates a closure where the inner function has access to the variable and its parameters.

javascript
// Define the closure function multFn() {   var mult = 9;   return function(val) {     mult = mult * val;     return mult;   } }  // Use the closure var mult = multFn(); console.log(mult(18)); 

Output:

162

1. Using private variables and methods: In JavaScript, we can use private variables and methods using closures. The example below shows the use of private variables with closure.

Example: In this example, the rentPrice() function returns an object with three methods: getRent(), incRent(), and decRent(). These three methods has access to the private variable rent. However, the code outside its scope cannot directly access this variable. Hence, we can mimic object oriented programming in JavaScript.

javascript
// Define the closure var rentPrice = function(initialRent) {    var rent = initialRent;      // Define private variables for     // the closure     return {       getRent: function() {         return console.log(rent);       },       incRent: function(amount) {         rent += amount;         console.log(rent);       },       decRent: function(amount) {          rent -= amount;          console.log(rent);       }     } }  var Rent = rentPrice(8000);  // Access the private methods Rent.incRent(2000); Rent.decRent(1500); Rent.decRent(1000);  Rent.incRent(2000);  Rent.getRent(); 

Output:

10000  8500  7500  9500  9500

2. Maintaining state between each function call: Suppose there is a function and one would like it to multiply multiple values together. This could be done with the help of a global variable as they are accessible throughout the program. However, a drawback is that they are prone to change from anywhere in the code. This can be done alternatively using closures. Closures help in maintaining the state between function calls without using a global variable.

Example:

javascript
(function() {    var multFn = function multiply() {     // This variable is local to     // the closure and holds     // its value inbetween     // multiple calls    var mult = 9;    return function(val) {      mult = mult * val;      return mult;    }   };    var mult = multFn();      // Call the method   // multiple times   console.log(mult(2));   console.log(mult(3));   console.log(mult(5)); }()); 

Output:

18  54  270

Next Article
What is a Constructor in JavaScript?

A

ashitace696
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Misc

Similar Reads

  • What is the use of let & const in JavaScript ?
    In this article, we are going to discuss the usage of let and const in JavaScript with the help of certain theoretical explanations along with some coding example as well. let: let keyword is used to declare variables in JavaScript that are actually to made as block-scoped i.e. it allows us to decla
    5 min read
  • What is a typical use case for anonymous functions in JavaScript ?
    In this article, we will try to understand what exactly an Anonymous function is, and how we could declare it using the syntax provided in JavaScript further we will see some examples (use-cases) where we can use anonymous functions to get our results in the console. Before proceeding with the examp
    4 min read
  • What is the Call Stack in JavaScript ?
    In JavaScript, the Call Stack is an essential concept that helps the JavaScript engine keep track of function execution. It plays a vital role in managing the execution order of functions and determining how the JavaScript program handles function calls. How Does the Call Stack Work?JavaScript opera
    4 min read
  • What is the (function() { } )() construct in JavaScript?
    If you've ever played around with JavaScript, you might have seen this expression. It's like a strange set of symbols, but it has a special name that is an immediately invoked function expression, or IIFE. In this article, we will understand each element of the expression as well as the functionalit
    3 min read
  • What is a Constructor in JavaScript?
    A constructor in JavaScript is a special function that is used to create and initialize objects. When we want to create multiple objects with similar properties and methods, the constructor is used as a blueprint to create similar objects. This is useful when you want to create multiple objects with
    8 min read
  • What is the usage of Function.prototype.bind in JavaScript ?
    Bind method: Using this method, we can bind an object to a common function, so that gives different result when its needed. The bind() method takes an object as an argument and creates a new function. So basically bind function return function. Let's understand when bind method is used. bind the obj
    2 min read
  • What is the syntax for leading bang! in JavaScript function ?
    Before we get to know the syntax for the leading bang! in a JavaScript function, let's see what functions in JavaScript are actually are. JavaScript functions are a set of statements(procedures) that perform some tasks or calculate some value. A function may take some input and return the result to
    2 min read
  • What is the first class function in JavaScript ?
    First-Class FunctionA programming language is said to have First-class functions if functions in that language are treated like other variables. So the functions can be assigned to any other variable or passed as an argument or can be returned by another function. JavaScript treats function as a fir
    2 min read
  • What is the drawback of creating true private methods in JavaScript ?
    According to other programming languages like c++, java, etc. private is something that can't be shared with other classes, which cannot be accessed directly using objects. The same rule applies to JavaScript also. So first we have to look at how private methods are made using JavaScript? There are
    3 min read
  • What are these triple dots (...) in JavaScript ?
    In JavaScript, there are multiple ways in which we can assign the value of one object to another. Sometimes we do not know the exact number of arguments that are to be assigned. In this case, the triple dots are used.  The triple dots are known as the spread operator, which takes an iterable(array,
    4 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