JavaScript: Arrow Functions for Beginners

Arrow functions were introduced with ES6 as a new syntax for writing JavaScript functions. They save developers time and simplify function scope. Surveys show they’re the most popular ES6 feature:

What Are Arrow Functions?

Arrow functions – also called “fat arrow” functions, from CoffeeScript - are a more concise syntax for writing function expressions. They utilize a new token, =>, that looks like a fat arrow. Arrow functions are anonymous and change the way this binds in functions.

Arrow functions make our code more concise, and simplify function scoping and the this keyword. They are one-line mini functions which work much like Lambdas in other languages like C# or Python. By using arrow functions, we avoid having to type the function keyword, return keyword (it’s implicit in arrow functions), and curly brackets.

Using Arrow Functions

There are a variety of syntaxes available in arrow functions, of which MDN has a thorough list.

In this tutorial, we’ll learn about another function usage in JavaScript known as an arrow function. In my opinion, this arrow function is so cool, especially if we’re talking about the efficiency of code writing in a program.

Definition

An arrow function expression is a syntactically compact alternative to a regular function expression. - MDN

How to make an Arrow Function In Javascript?

Before that, let’s see the function expression usage first:

    // Function Expression

    const myFunction = function (name) {
        return `Hello, ${name}`;
    }

    console.log(myFunction('Ridwan')); 

To make these function expression to be an arrow function, see the basic syntaxis below:

    const functionName = (param) => { return `String literal, ${param}`; }

Note: The arrow function is using a template/string literal. Template literals are enclosed by the backtick ( ).

Example:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <title>Document</title>
    </head>

    <body>

    <script>
        const myFunction = (name) => {
            return `Hello, ${name}`;
        }
        console.log(myFunction('Ridwan'));
    </script>
    </body>

    </html>

Result:

Javascript function: Arrow function - example 1

If you have more than one parameter, you can use these following syntax:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <title>Document</title>
    </head>

    <body>

    <script>
        const myFunction = (time, name) => {
            return `Good ${time}, ${name}`;
        }
        console.log(myFunction('Mornig', 'Ridwan'));
    </script>
    </body>

    </html>

Result:

Javascript function: Arrow function - example 2

If you only have one parameter and the function is only returning a value, you can make it more compact like this example:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <title>Document</title>
    </head>

    <body>

    <script>
        // implicit return

        const myFunction = name => `Hello, ${name}`;
        console.log(myFunction('Ridwan'));
    </script>
    </body>

    </html>

These called implicit return, and the arrow function still runs well the same as before:

Javascript function: Arrow function - example 3

And the last examples of the usage this arrow function is when the program doesn’t have a parameter the arrow function must contain empty parentheses “( )” symbol.

Example:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <title>Document</title>
    </head>

    <body>

    <script>
        const myFunction = () => `Hello World!`;
        console.log(myFunction());
    </body>

    </html>

Result:

Javascript function: Arrow function - example 5

Arrow Function with Function Map

You’ve seen the basics of arrow functions usage before. Now, let’s try another example of an arrow function with a function map in javascript. For example, we’ll try to count all the characters on some names, and we’ll try to change the result from returning an array and then make it as an object.

Let’s start with returning an array.

Example:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <title>Document</title>
    </head>

    <body>

    <script>
        let peoples = ['Ridwan Fadilah', 'Jhon Due', 'Mike Wazowski'];
        let allChar = peoples.map(name => name.length);
        console.log(allChar);
    </body>

    </html>

And the result will display by the browser console like this:

Javascript function: Arrow function - example 6

To make it an object, you must use the curly braces and the parentheses “({ })”
I’ll try to get the object name and counting all the characters of the names. In this case, the function also must have a property and fills by the parameter/argument.

    (param => ({ property: param )})

Here’s the example:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <title>Document</title>
    </head>

    <body>

    <script>
        let peoples = ['Ridwan Fadilah', 'Jhon Due', 'Mike Wazowski'];
        let allChar = peoples.map(name => ({
            name: name,
            charLength: name.length
        }));
        console.log(allChar);
    </body>

    </html>

Result:

Javascript function: Arrow function - example 7

In the newest javascript, you can remove the property name if the property same as the parameter.

Example:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <title>Document</title>
    </head>

    <body>

    <script>
        let peoples = ['Ridwan Fadilah', 'Jhon Due', 'Mike Wazowski'];
        let allChar = peoples.map(name => ({
            name,
            charLength: name.length
        }));
        console.table(allChar);
    </body>

    </html>

I use the “console.table()” to make it look good:

Javascript function: Arrow function - example 9

The “this” in Arrow Function

Arrow function does not have the ‘this’ concept. When we use the ‘this’ concept in a constructor function, it will work so well. In other functions, the ‘this’ will represent the object that could be the window, document, button or whatever.

It so different if we are using the arrow function. With arrow functions, the ‘this’ always represents the object that defined the arrow function.

Example:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <title>Document</title>
    </head>

    <body>

    <script>
        const person = {
        name: 'Ridwan',
        sayHello: function () {
            console.log(`Hello, my name is ${this.name}.`);
        }
    }
    </body>

    </html>

When we type and call the function ‘person.sayHello()’ there is no problem:

Javascript function: Arrow function - example 9

And if the arrow function is used:

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <title>Document</title>
    </head>

    <body>

    <script>
        const person = {
        name: 'Ridwan',
        sayHello: () => {
            console.log(`Hello, my name is ${this.name}.`);
        }
    }
    </body>

    </html>

The name is undefined or blank:

Javascript function: Arrow function - example 10

That’s just a simple way of arrow function usage. In the real case, we’ll not be able to use it on a program with more high complexity.

Thanks!


JavaScript ES6 Arrow Functions Tutorial

ES6 added many amazing new features to JavaScript, but by far one of the best features is arrow functions. Arrow functions not only make code much more concise and legible, but it also handles the scope of this in a much more intuitive way.


ES6 Arrow Function - Topics of JavaScript/ES6

In this video, I cover anonymous functions with the arrow syntax in ES6 JavaScript.


Arrow function basics in javascript 😃

#javascript #web-development #es6

JavaScript: Arrow Functions for Beginners
20.70 GEEK