Understanding Closures In JavaScript Day 5

Lecture 5 : Understanding Closures In JavaScript


Closure :
  • Closure is one of important concept in JavaScript. It is widely discussed and still confused concept.

  • Most of the JavaScript developers use Closures consciously or unconsciously.

  • Even if they do unconsciously it works fine in most of the cases. But knowing closure will provide better control over the code when using them.
  • And another reason for learning closure is that it is the most frequently asked question in the interview for the JavaScript developers.
  • Closure means that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.
The Lifetime of JavaScript Variables :

1) Local Variable
2) Global Variable

                -The lifetime of JavaScript variable starts when it is declared.

1) Local Variable :
  • Local variables are declared when the function is completed.

  • A function can also access variables defined outside the function.

                    var a = 4;
                    function myfunction()
                    {
                       return a * a;
                     }

2) Global Variable :
  • Global variables are declared when you close the browser window (or tab).

  • A function can also access variables defined inside the function.

                    function myfunction()
                    {
                       var a = 4;
                       return a * a;
                     }

Scope :
  • Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript.

  • The two types of scope are local and global

    1. Global variables are those declared outside of a block. 
    2. Local variables are those declared inside of a block.

Understanding Closures :
  • Closures have been hard to explain traditionally because, despite their usefulness, they work silently in the background to make things work, the stuff we take for granted. In this article, I’ll try to cover the basics of what a closure is and why JavaScript benefits from closures.

  • A closure can be defined as a persistent scope that is held onto by a variable. Languages like JavaScript and Ruby support closures, which allows variables to have references to their parent scope even after their programming block has been executed and, as long as these variable have a reference somewhere, the closure exists.

Example :

Program-

<html>
<body>
<script>
function fun()
{
    var name = "ClosuresJavaScript";
    function displayname()
    {
        alert(name);
    }
        return displayname;
}
var myfun = fun();
myfun();
</script>
</body>
</html>

Output-


Comments

Popular posts from this blog

Basic Concept In C Sharp Day 16

Understanding C Sharp Day 18

Learn Garbage Collection Day 21