Research Closures - mikehov/Dating-app GitHub Wiki
Closures Research
Mike Hovenier | Tech-4
What are Closures
A closure is a feature, it gives you access to an outer function from an inner function, even though the functions are nested inside each other (enclosed). So that means if you enclose an inner function, it's able to get acess to the outer function. So every scope has acess to everything outside of it's scope. Closures get made all the time when you make a function. Closures isn't something, it's a type of thinking and giving your code a clearer structure for in the long run. An inner and an outer function look like this:
An example of closures:
const myName = 'Mike'
function printName() {
console.log(myName);
}
printName(); // Mike
The variable myName
will be available inside the function even though the variable is outside the function, so printName();
will say: Mike. If you define myName multiple times, in other words changing its value. The value of printName();
will change, depends on where you define it. As long as it's been defined before it's been called. But, you can't change const
so it needs to be a let
instead.
An example of closures (functions in functions):
// outerfunction
function outerFunction() {
const outside = 'house';
// innerfunction
function innerFunction() {
const inside = 'people';
console.log(outside + ' ' + inside);
}
return innerFunction();
}
outerFunction(); // house people
In the example above two functions are inside eachother. The function outerFunction();
will log: house people. Even though const inside = 'people';
isn't in the outerfunction. The outerFunction();
has still acess to the variable of the innerFunction();
cause of the closures.
How can I use Closures for my project?
The holding structure and make things only accessible if I need to. My feature has a few functions:
-
Array with Id's:
- Loops through all Id's of the database.
- Filters your own Id out
-
Like and Dislike:
- When you hit the like or superlike button, it adds that ID of that person to your profile into the like array.
- When you hit the dislike button, it adds that ID of that person to your profile into the dislike array.
-
Notification:
- You liked someone, someone likes you, its a match, after the click on a button it will send you to the notification page of that person.
Source
Closures. (2020, May 16). Retrieved May 28, 2020, from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
The Coding Train. (2015, December 4). 9.6: JavaScript Closure - p5.js Tutorial [Video file]. YouTube. Retrieved from https://www.youtube.com/watch?v=-jysK0nlz7A
Web Dev Simplified. (2019, December 3). Learn Closures In 7 Minutes [Video file]. YouTube. Retrieved from https://www.youtube.com/watch?v=3a0I8ICR1Vg