DEV Community

Cover image for JavaScript 101: Arrow Functions
Kara Luton
Kara Luton

Posted on • Updated on

JavaScript 101: Arrow Functions

Arrow functions - they're the more concise version of regular functions and they've been gaining popularity since they were first introduced in ES6. Not only is the syntax much cleaner but they also provide implicit returns which we'll dive into.

Hold up! If you haven't read the first part in this series, JavaScript 101: Breaking Down Functions, then make sure to check that out.

Let's start with how the arrow function's syntax is different from regular functions.

Here we have a regular function:

function helloWorld(name) {
 console.log('Hello ' + name);
}
Enter fullscreen mode Exit fullscreen mode

If we wanted to use an arrow function, it would look like this:

const helloWorld = name => {
  console.log('Hello ' + name);
}
Enter fullscreen mode Exit fullscreen mode

There are some key differences with arrow functions. We've dropped having to declare the function using the function keyword. Our parameters are a bit different than before as well. They now come after an equal sign and before the fat arrow (=>).

You may have also noticed that we're now declaring our arrow function as a variable. That's because arrow functions are anonymous functions or functions that are declared without a name. You don't have to assign them to a variable but doing so allows you trace them more easily when you have an error.

🌟 Quick tip: If you only have one parameter the parentheses are optional. If you don't have any parameters then you'll need to use empty parentheses.

Here's our example with multiple parameters:

const helloWorld = (name, emoji) => {
  console.log(emoji + ' Hello ' + name);
}
Enter fullscreen mode Exit fullscreen mode

And our example with no parameters:

const helloWorld = () => {
  console.log('Hello');
}
Enter fullscreen mode Exit fullscreen mode

Now that we've covered the syntax of arrow functions let's talk about another big benefit - implicit returns! This will make your code even shorter than before. Let's take the example we've been using and switch to a return instead of a console.log.

const helloWorld = name => {
  return 'Hello ' + name;
}
Enter fullscreen mode Exit fullscreen mode

Because we're only returning a single line of code we can use the arrow function's ability to do an implicit return and rewrite our function like so:

const helloWorld = name => 'Hello ' + name;
Enter fullscreen mode Exit fullscreen mode

When utilizing implicit returns, you're able to drop the return keyword as well as the curly brackets. This makes for really nice one-line functions.

Implicit returns aren't the only big difference between arrow functions and regular functions. Another big one is how they handle the this keyword.

In regular functions, the this keyword is bound depending on the context in which it was called. However, inside of arrow functions, this is lexically bound meaning that it's static and determined by the scope that it's in.

This is still something that I'm trying to grasp myself but JavaScript Kit has a great explanation if you're wanting to dive in more.


Be sure to follow me on Twitter for lots of posts about tech, and if I'm being honest, lots of posts about dogs too.

Top comments (26)

Collapse
 
zeddotes profile image
zeddotes

The lexically bound this context is probably the most important quality of thicc arrow functions.

Collapse
 
andrewbrooks profile image
Andrew Brooks 👨‍💻

Agreed. It helps with some of the strange and unexpected behavior of this.

Collapse
 
sameerchandra profile image
Sameer Chandra Nimushakavi

Being a react developer, I mostly use arrow functions to bind this context

Collapse
 
davegomez profile image
David Gómez

You are not binding the context by using an arrow function, it doesn't work that way.

More info here: github.com/getify/You-Dont-Know-JS...

Collapse
 
itsjzt profile image
Saurabh Sharma

I tend to use hooks in new code and avoid this altogether.

Thread Thread
 
daveclarke profile image
daveclarke

Can you please provide an example of this (using hooks not this).

Thread Thread
 
itsjzt profile image
Saurabh Sharma

why would you need this when you don't use classes.

Thread Thread
 
daveclarke profile image
daveclarke

Sorry I'm just confused what you mean by hooks. Hoping you might paste in an example?

Thread Thread
 
itsjzt profile image
Saurabh Sharma

Classical React example of Counter

class App extends React.Component {
    constructor(props) {
        this.state = {
            count: 0
        }
    }

    onClick(e) {
        this.setState({
            count: this.state.count + 1
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                {/* this is needed here  */} 
                <button onClick={this.onClick.bind(this)}>Count Up!!</button>
            </div>
        )
    }
}

and after using React Hooks

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

know more about react hooks.

Collapse
 
drozerah profile image
Drozerah • Edited

Implicit return:

When returning an Object, remember to wrap the curly brackets in parentheses to avoid it being considered the default wrapping function body brackets:

const myFunction = () => ({value:'test'})

console.log(myFunction()) // { value: 'test' }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
c24w profile image
Chris Watson

And remember to write tests so you catch these mistakes :)

Collapse
 
drozerah profile image
Drozerah • Edited

We wish to read you about tests - from scratch - if you have time to start a serie about that topic... ;)

Collapse
 
abdurrkhalid333 profile image
Abdur Rehman Khalid

When I first saw the Title and I thought it is going to be something strange but it came out as the Lambda Functions that is being used in the Higher Versions of Java, by the way as I am a JavaScript Developer as well so it is very nice post according to that as well :)

Collapse
 
davegomez profile image
David Gómez

The arrow function is by definition a lambda function, is not just syntax.

Collapse
 
sambajahlo profile image
Samba Diallo

Concise and easy to understand, love learning little new bits and pieces about JS!
The this keyword has shortened my coding time by a lot in my recent projects.

Collapse
 
karaluton profile image
Kara Luton

Thank you!

Collapse
 
valentinogagliardi profile image
Valentino Gagliardi

Hi Kara I think there's a missing const in the very first snippet :-)

Collapse
 
karaluton profile image
Kara Luton

Ah thank you! I meant to get rid of setting that variable at all actually.

Collapse
 
namstel profile image
Namstel

A nice quick read with usefull information. I didn't know it does an implicit return. I'm still not sure how this works, but I'll look that up.

Thanks!

Collapse
 
karaluton profile image
Kara Luton

Thank you!

Collapse
 
philsinsight profile image
Mr. Boateng

Great post! Also really appreciate the link to a deeper insight of how the keyword works with arrow functions.👌

Collapse
 
mgranados profile image
Martín Granados García

Nice post! Truly helpful as I never took the time to truly master the arrow function

Collapse
 
scrabill profile image
Shannon Crabill

Arrow functions make more sense to me know that I know about hashes in Ruby 🤔

Collapse
 
ashikpaul42 profile image
AshikPaul42

How do we write a return type in an arrow function?

Collapse
 
joewilson0 profile image
Joe Wilson

Nice write up, Kara.

Collapse
 
karaluton profile image
Kara Luton

Thank you!