It is one of the important concept, mainly used by the JavaScript developers.
Let me explain it further with a suitable example:-
closure.html:-
Let me explain it further with a suitable example:-
closure.html:-
<html>
<head>
<body>
<script src="app.js">
</script>
</body>
</html>
app.js:-
function showValue (x, y) {
var value = "The value is ";
function makeSentence () {
return value + x + y;
}
return makeSentence ();
}
console.log(showValue (5, 6));
Output:-
Explanation:-
Here, "showValue()" ia the function name, passed with two parameters - "x" & "y". A variable called "value" has been declared inside it. A function name called "makeSentence()" has been declared, which is the inner function of the outer function - "showValue()". This inner function - "makeSentence" has access to the outer function's("showValue()") variable("value"), including the parameters("x" & "y"). The "value", "x" & "y" has been returned in the inner function, by using "return" keyword. So, the output will be "The value is 56", as "+" operator is used which will concatenate the numbers.
No comments:
Post a Comment