When a function is created the function saves the states of the variables in its outer scope. During running that function it can access it. Closure is called this feature where inner function has access to outer functions variables.
function A() {
let a = 1,
b = 2; //these remain private
function calculate() {
return a + b;
}
const calculateArrow = () => {
return a + b;
};
return {
get: calculate, // public function will be only get
getArrow: calculateArrow, // this also works
};
}
const a = A();
console.log(a.get()); // 3
class Dashboard extends Component {
render() {
const { name } = this.props;
function printName() {
// you have written probably functions like this
// many times without noticing that Im not passing the name
// as a param for this function :P
console.log(name);
}
const printNameArrow = () => {
// Arrow functions can also access parents variables
console.log(name);
};
return (
<div onClick={printName}>
<span>{name}</span>
</div>
);
}
}
Yes they are also accessible and changeable
function B() {
let c = 10;
let b = 10;
function A() {
let a = 1,
b = 2; // this is overridden with the previous b in parent
function calculate() {
return a + b;
}
const calculateArrow = () => {
return a + b + c; // it can see variables from all around its scope
};
const change = () => {
c = 5;
};
return {
get: calculate, // public function will be only get
getArrow: calculateArrow, // this also works
change: change, // can also change variables from grand parents
};
}
return A;
}
const a = B()();
console.log(a.getArrow()); // 13
a.change();
console.log(a.getArrow()); // 8
for (let i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
// output: 0 1 2 3 4
I hope you don't use var :(
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
}
// output: 5 5 5 5 5
