-3

I am learning javascript and I can't understand what is the purpose of anonymous function in JS, Why we use them ? I found in many tutorials that anonymous function is used to hide local variable.
I am learning from MDN : and they said :

"a way of "hiding" some local variables — like block scope in C"

Can explain me this please ?

DeltaWeb
  • 381
  • 2
  • 14

1 Answers1

0

You say anonymous functions can hide local variables. By introducing an anonymous function, you can declare variables within it that are not accessible from outside. This is an IIFE:

var x = 5;

(function() {
    var y = 3;

    // x and y are visible  
    console.log(x);
    console.log(y);
})();

// Only x is visible
console.log(x);
//console.log(y); // y is undefined

There are other uses of anonymous functions. For example, when registering event handlers or calling a function with a callback like:

([1, 2, 3]).forEach(function(x) { console.log(x) });
fgb
  • 18,439
  • 2
  • 38
  • 52