When and why to use arrow functions
What is scope?
Scope is the accessibility of variables and functions from the current location in the code, which limits your view from the current location to give better structure.
Global scope
Scope is global by default, for example when declaring a variable in a JS file. Global scope is reachable anywhere
var a = 'a';
console.log(a); // prints a
function test() {
console.log(a); // prints a
}
Local scope
One way to limit your scope is with local scope:
function test() {
// local scope with function
var a = 'a';
console.log(a); // prints a
}console.log(a); // doesn't work
Local scope can reach global scope but not vice versa. Local scoped variables and functions can be declared inside classes, functions or modules.
Block scope
function testFunction() {
var a = 'a';
}for (var i = 0; i < 10; i++) {
// Block scope
}
console.log(a); // ReferenceError: a is not defined
console.log(i); // prints 10
The keyword var behaves differently in function and block scope, it cant be accessed outside function scope, but can be accessed outside block scopes. That is why the use of let/var, they behave the same in function and block scope and are scoped locally within.
for (let i = 0; i < 10; i++) {
// Block scope
}
console.log(i); // ReferenceError: i is not defined
Arrow function
Arrow functions came with es6 and the primary reasons for its need was shorter function and no explicit this. Arrow functions doesn’t have the its own this, argument, super or new.target. Instead arrow functions bind this to the surrounding function. Before arrow functions we hade to write this:
function Person() {
this.age = 0;
var self = this;
setInterval(function() {
self.age++;
}, 5000);
});var p = Person();
With arrow function we can instead write this:
function Person() {
this.age = 0;
setInterval(() => {
this.age++;
}, 5000);
});var p = Person();
Arrow functions doesn’t use global or local scope, but lexical scope.
Lexical scope
Lexical scope means that since it doesn’t have its own local scope, it uses the scope of then enclosing scope. Which in the former example means that in setInterval we have access to the other scope of Person.