JavaScript Flashcards
What is a closure ?
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables - a scope chain.
Whenever you create a function within another functions, you have created a closure. The inner function is the closure.
This closure is usually returned so you can use the outer function’s variables at a later time.
The closure has three scope chains:
- it has access to its own scope – variables defined between its curly brackets.
- it has access to the outer function’s variables.
- it has access to the global variables.
The variables inside the functions only come into existence when the function is running, and cease to exist once the functions completes execution.
function createCounter(){ let counter = 0; const myFunction = function(){ counter = counter + 1; return counter; }; return myFunction; }; const increment = createCounter() const c1 = increment() const c2 = increment() const c3 = increment() console.log('example increment', c1, c2, c3) // example increment 1 2 3
Whenever you declare a new function and assign it to a variable, you store the function definition, as well as a closure. The closure contains all the variables that are in scope at the time of creation of the function.
What is a scope ?
A scope in JavaScript defines what variables you have access to. There are two kinds of scope - global scope and local scope.
What is the global scope ?
If a variable is declared outside all functions or curly braces ( {} ), it is said to be defined in the global scope.
What is the local scope ?
Variables that are usable only in a specific part of your code are considered to be in a local scope. These variables are also called local variables.
In JavaScript, there are two kinds of local scope: function scope and block scope.
What is the function scope ?
When you declare a variable in a function, you can access this variable only within the function. You can’t get this variable once you get out of it.
What is the block scope ?
When you declare a variable with const or let within a curly brace ( {} ), you can access this variable only within that curly brace.
The block scope is a subset of a function scope since functions need to be declared with curly braces. (unless you’re using arrow functions with an implicit return).