Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?

1 Answer

0 votes
by (106k points)
edited by

JavaScript closures works whenever they see the function keyword within another function, the inner function has access to variables in the outer function. Below is an example that shows how closure works in JavaScript.

function foo(x) {

var tmp = 3;

function bar(y) {

console.log(x + y + (++tmp));

  } 

bar(10); 

 } 

foo(2);

image

This code will always print 16 because the function bar can access the value x which was defined as an argument to function foo, and from foo, it can also access tmp.

Are you willing to pursue a career in Web Development, here's an opportunity for you Web Developer Certification provided by intellipaat!

Related questions

0 votes
1 answer
asked Feb 6, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
+2 votes
1 answer

Browse Categories

...