1.

Is there any <noscript> element in JavaScript?

Answer»

JavaScript Closures

A closure is a FUNCTION in JavaScript which have access to the parent scope, even after closing the parent function.

Let us see an EXAMPLE:

<!DOCTYPE html> <html> <body> <p>Increment by 5</p> <button type="button" onclick="show()">Count!</button> <p ID="myid">0</p> <script>   var sum = (function () {   var count = 0;   return function () {count += 5; return count;} })(); function show(){   document.getElementById("myid").innerHTML = sum(); } </script> </body> </html>

The output: 

After clicking “Count” above, the value increments by 5: 

In the above example, the following VARIABLE is assigned the return value of a function which is self-invoking: 

var sum = (function () {

The self-invoking function sets the count to zero:

var count = 0; return function () {count += 5; return count;}

It returns a function expression as you can see above. This makes it a function and can access the count in the parent scope as well. This is what we can call closure in JavaScript.

Anonymous functions

Creating a function without a name is what we call Anonymous functions. Let us see an example:

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var res = function (val1, val2, val3) {return val1 * val2 * val3}; document.getElementById("demo").innerHTML = res(5, 10, 15); </script> </body> </html>

The output: 

750

Above, we have function without a name:

var res = function (val1, val2, val3) {return val1 * val2 * val3};


Discussion

No Comment Found