(arrow) Function Junction =>
ECMAScript 6 introduced simple and clean-looking arrow functions. These functions are beautifully concise but can sometimes cause scoping issues because they are anonymous function expressions and are treated just like any other variable. One place that I find arrow functions particularly useful is when a function does one thing because you can shorten and clean up your code with a one-liner. One thing to keep in mind is that arrow functions anonymous, so debugging can prove to be more difficult at times. Additionally, arrow functions are not self-binding, so things like recursion will not work. The primary benefit of an arrow function is that there is no binding of the this
keyword.
To convert a ‘classical JavaScript’ function into a modern arrow function, simply replace the word function with const or let, followed by a variable name, then parenthesis in which you pass your arguments, and finally the fat arrow like so: const nameFunc = ()=>{}
To reiterate, all arrow functions are anonymous function expressions. These differ from function declarations in that they are evaluated as part of the step-by-step code whereas function expressions are hoisted and called immediately. Using classical JS you can also write an anonymous function expression with: const foo = function() {}
or a function declaration: with function foo() {}
.
This anonymity can be particularly useful in places such as in a constructor because of the binding that goes up the scope. You can therefore use this
within a constructor method to refer to the constructor itself.
Another amazing capacity that ES6 gave us is the ability to destructure an array or object. This is essentially a way to grab values out of an array/object without repeating yourself. For instance, to give each item in an array a variable name in classical JS you would have to do the following:
let arr = ['1', '2', '3', '4', '5']let index0 = arr[0];
let index0 = arr[1];
let index0 = arr[2];
let index0 = arr[3];
let index0 = arr[4];console.log(index0) // '1'
console.log(index1) // '2'
console.log(index2) // '3'
console.log(index3) // '4'
console.log(index4) // '5'
This is not very D.R.Y. code at all. However, we now have a much better way to do the same thing!
let arr = ['1', '2', '3', '4', '5']let [index0, index1, index2, index3, index4] = arrconsole.log(index0) // '1'
console.log(index1) // '2'
console.log(index2) // '3'
console.log(index3) // '4'
console.log(index4) // '5'
Ahhhhh. Much better, much cleaner, much more concise.
One more concept to introduce today: closure. Closure refers to a function within another function having access to the outer function’s scope. Scope in JS can be a confusing topic but basically, each child has access to the scope of its parent but not vice versa and nothing else can access that scope. Make sense? If not, here’s some additional reading: