Is this function a closure in javascript?

    function f1(){
        var n=999;
        function f2(){
            alert(n); // 999
        }
    }

is the function f2() a closure? if not? why?

what’s and use of a closure.could you depict it in your own words. thank you

It’s not a closure. It’s just a function declaration.

If the f1 function returned a reference to the f2 function, that returned f2 function will then form a closure over the variables from the f1 function.

Here’s the best explanation of closure that I’ve come across.
How do JavaScript closures work?

your mean that if i call the f1(). then f2() will be a closure?

a closure will form if a function B in a function A. and function A is called. then function B is a closure. am i right? thank you.

No, it won’t. It would only be a closure if the f1 function returned a reference to the f2 function.

No. The closure would be on the variable “n” but only if the f1 function returned the f2 functon so that f2 can be called after f1 has already finished running (and where the “n” variable would have already gone out of scope except for the fact that there is still a way to reference it via f2.

The following would be a closure:

    function f1(){
        var n=999;
        function f2(){
            alert(n); // 999
        }
        return f2;
    }

a = f1();

a();

With that code the last line a() will run the alert to display the 999 even though the call to f1 completed and n would have gone out of scope except for the closure.

felgall, your mean a closure will be:fuction B in function A. and in function A. there must be fuction B. then to function A’s variable. fuction B is a closure. am i right?

felgall. to sum it up. according to your answer. the benefit of the closure is if outside the function. i can use the closure(f2) to reference the variable(on the above is n). am i right?thank you.

anyone knows? am i right?

That seems to be right.