I am preparing for a job interview as a JS developer and I bumped into this closure definition:
A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in the parent function scope.
Let's consider two different pieces of code:
function a() {
const temp = 1;
function b() {
console.log(temp);
}
}
So obviously function b
is a closure, because it was declared inside function a
and has access to its variable temp
.
But what if I declare just a function just like that, without an IIFE:
function c() {
alert("Hi") // a function taken from the global scope
}
My c
function wasn't declared inside any function, yet it has access to the global scope. Can it be called a closure, or should it be specifically declared inside another function to be called one?