Code: Arrow function syntax
When first learning how to code, one of my biggest struggles was understanding the syntax, and how one function or method could be written in so many different ways. Although it’s quite intimidating, and it’s often based on the personal preference of the programmer, so don’t be alarmed! I’m going to walk you through some examples to hopefully help you understand the differences between regular functions and arrow functions — and the different ways arrow functions can be written. Here we go:
Let’s first compare the syntax of an arrow function v. regular function:
Functions can get quite long and a bit complex. A great benefit in using arrow functions…is the syntax is shorter. Although this may not be the best example to illustrate this — they often allow for easier readability and take up less written code.
Shorter Syntax:
Breaking down arrow function syntax:
- Arrow functions with parameters: In this first example we see how a function is written when parameters are passed in. After the arrow we open up our block and write in what we want our function to execute — our statement.
2. Arrow functions without parameters: In this example below we see how a function is written when there are NO PARAMETERS to be passed in. And just as we did before…after the arrow we open up our block to write our execution statement.
3. Returning with arrow functions: when you are returning ONLY one line of code you DO NOT need brackets or the word return. The syntax can be simplified from Example 1 to Example 2 → removing the bracket and the return word.
Arrow functions → DO NOT bind this:
- Example of arrow functions & lexical context: it is important to remember that arrow functions do not bind this. We use bind with regular function expressions. With arrow functions the value of this is always defined within its lexical context. To see how the below example works copy and paste into your console — and note that the value of this in your console is always your window → (if you simply type this in your console you will return your window object)
In our example below the lexical…and in this case the global…context of this is our window object → and so when we call our functions we return true.