# Arrow Functions
Arrow functions brought a simplified syntax to writing functions in JavaScript.
//instead of writing
function add(a, b) {
return a + b;
}
//we could write
(a, b) => a + b;
1
2
3
4
5
6
2
3
4
5
6
Arrow functions are great in places where you would use an anonymous function or a small pure function with only one or two lines of code.
Sometimes, due to the brevity, it can appear a little more cryptic.
There is one other change with Arrow functions that will become more important as your code grows in complexity.
Arrow functions use lexical scoping
for determining the value of this
. Instead of using the four standard this rules, arrow-functions adopt the this
binding from the enclosing (function or global) scope. Simply put, an Arrow function will use whatever value you would get for this
if you wrote it on the line above where the function is declared.
function foo() {
// return an arrow function
// when called through foo.call(obj1), obj1 is the value of `this`
return (a) => {
// `this` here is lexically adopted from `foo()`
console.log(this.a);
};
}
let obj1 = {
a: 2,
};
let obj2 = {
a: 3,
};
let bar = foo.call(obj1);
bar.call(obj2); // 2, not 3!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19