Today you will learn:
let and constBy the end, you will understand how variables live and behave in JavaScript functions.
Scope defines where a variable is accessible.
let and const, variables are limited to the block they are defined inA closure is a function that “remembers” the variables from the scope it was created in, even after that scope has finished.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Explanation:
inner function has access to count even after outer finished executing
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Create a counter function using closure that:
Example:
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const myCounter = createCounter();
console.log(myCounter()); // 1
console.log(myCounter()); // 2
console.log(myCounter()); // 3