Lesson 8 of 15By Simplilearn
Last updated on Jul 10, 20202022Programmers frequently use JavaScript Closures. Many might not be aware of exactly what a closure is, although its results are present. Nevertheless, it’s always better to have practical knowledge of such concepts. This article on JavaScript Closures covers the following topics:
The location of the variable declaration generally defines the scope of a variable. It defines the part of the program where a particular variable can be accessed. JavaScript supports two types of variable scopes -
A variable declared outside of a function is attributed to the global scope and is hence accessible from anywhere in your code.
Local Variables or Function Variables are variables declared within a function. These variables are only accessible from that function and its nested functions.
<script>
var a = 10
function function_Name(){
var b = 20;
document.write(“The sum is “ + (a+b) + '<br>')
}
function_Name()
<script>
Variable Scope
Now that you know what variable scope let’s understand what exactly is JavaScript Closure
Closures in JavaScript is a feature where an inner function has access to the outer function’s variables. Closures are important as they define what is and what isn’t in the scope of functions. They also control the variables that are being shared with the nested functions.
A closure –
<script>
var a = 10
function First_func()
{
var b = 20;
function Second_func()
{
var c = 20+a+b
return c
}
return Second_func();
}
var sum = First_func()
document.write("The sum is " + sum)
</script>
JavaScript Closures
Master JavaScript fundamentals including, jQuery, Ajax, and more with the Javascript Certification Training Course. Check out the course preview!
To learn more about JavaScript in its entirety, certification is highly recommended and could act as a catalyst for enriching your coding career. Simplilearn's JavaScript Certification Training course helps individuals master the JavaScript programming language in an all-inclusive training program that includes complete JavaScript fundamentals, jQuery, Ajax, and more. You will also have the opportunity to apply your skills by building a real-time chat application.
Do you have any questions regarding JavaScript Closures? Let us know in the comments section of this article. Our experts will get back to you as soon as possible!
Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.