Sunday, 24 July 2016

JavaScript Function Scope and Closures

Scope
scope refers to an area within which a function and its variables are accessible.
Functions can have two scope

  • Global - specifies that a function can be accessed from anywhere in the program.
  • Local - specifies that a function can be accessed within the parent function.
Closure
A closure is a variable that is created inside a function and continues to exist after the function has finished executing.

Example
<!DOCTYPE html>
<html>
<head>
    <title>javaScript function scope</title>
</head>
<body>
    <h1>JavaScript function scope</h1>
    <script>
        function func_global()
        {
            var name = "closure";
            func_local();
            function func_local(name)
            {
                document.write("I am in Local Scope  <br />");
            }
            document.write("I am in Global Scope & name is " + name);
        }
        func_global();
    </script>
</body>
</html>



0 comments:

Post a Comment