Today’s Panic: Arrow Function Syntax
What are Arrow Functions?
The textbook definition, according to MDN Web Docs is: An arrow function expression is a compact alternative to a traditional function expression, but is limited and can’t be used in all situations.
TLDR — Limited compact function alternative.
What are the key differences?
- Does not have its own bindings to
this
orsuper
- Should not be used as
methods
. - Does not have
new.target
keyword. - Not suitable for
call
,apply
andbind
methods, which generally rely on establishing a scope. - Can not be used as constructors.
- Can not use
yield
, within its body.
Breaking Down the Syntax
We can think of arrow function syntax as having two forms: Basic and Advanced.
There are four (4) variations of the basic form, each with its own syntactical nuances:
- One Param — The first and most basic variation.
- Multiple Params — The second allows programmers to account for multiple (2+) parameters.
- Multi-Line Statements — The third allows programmers to create more complex code blocks within their function. For example, programmers can declare another variable within the function (as seen below).
- Multi-Line Multiples — The fourth is a combination of two and three, bringing together the elements of multiple parameters with a multiline codeblock.
While the basic forms serve as the foundation for building your arrow functions, there are also advanced syntactical structures that allow programmers to incorporate other code features into their functions (e.g. destructuring).
These advanced forms include:
- Returning an Object — A way for programmers to have arrow functions return object literal. REMEMBER to place parentheses around the object otherwise it will not function (pun intended) properly.
- Rest Parameters — This allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.
- Default Parameters — Allow named parameters to be initialized with default values if no value or
undefined
is passed.
- Destructuring — Javascript Syntax that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
And this has been an introduction to basic Arrow Function Syntax. Check ou this video for more beginner’s info on Arrow Functions!