Activity Forums Salesforce® Discussions Why do we use Closure in Javascript?

  • Naman

    April 14, 2016 at 8:05 am
  • Abhinav

    April 14, 2016 at 8:13 am

    I've used closures to do things like:

    a = (function () {
    var privatefunction = function () {

    return {
    publicfunction : function () {

    As you can see there, a is now an object, with a method publicfunction ( a.publicfunction() ) which calls privatefunction, which only exists inside the closure. You can NOT call privatefunction directly (i.e. a.privatefunction() ), just publicfunction().

    Its a minimal example but maybe you can see uses to it? We used this to enforce public/private methods.

  • Parul

    September 19, 2018 at 11:47 pm


    Because javascript doesn't have feature like namespaces, and you can mess up pretty easily with all sort of global objects.

    So it is important to be able to isolate some code in its own execution environment. Closure are perfect for that.

    Hope this helps

Log In to reply.

Popular Salesforce Blogs

Steps to Connect Pardot to Salesforce

Steps to Connect Pardot to Salesforce

Blog in

Steps to Integrate Salesforce and Pardot: There are some steps to install Pardot in salesforce 1- Click on this link (sandbox) 2- After…

Popular Salesforce Videos