Zak Dyer

Zak Dyer

1562574815

Getting Started with ES6 Arrow Functions in JavaScript

With ES6 JavaScript came many updates to the language including the spread operator, object destructuring, new type of variables, and more. On top of all those amazing features came arrow functions, a new and concise way to write functions.

Table of Contents

  • ES5 Functions
  • Your First ES6 Arrow Function
  • Removing Unnecessary Parenthesis
  • Implicit Return
  • Using Arrow Functions in Map and Filter
  • ‘This’ Binding with Arrow Functions
  • Wrap Up

ES5 Functions

Let’s start with looking at how we defined functions with ES5 JavaScript. To do define a function, it required the function keyword. For example, if we wanted to define a function that would multiply a number by two, it would look something like this.

function multiplyByTwo(num){
    return num * 2;
}

We could also define the function and assign it to a variable if we wanted to.

const multiplyByTwo = function(num){
    return num * 2;
}

Regardless of which way you do it, the keyword function has to be included.

Your First ES6 Arrow Function

To create an arrow function, you don’t need the keyword function. In fact, you basically remove that keyword and add an arrow right after the parameters but before the open curly bracket. It would look like this.

const multiplyByTwo = (num) => {
    return num * 2;
}

At this point, it doesn’t look substantially different than the “old” way to do it, but we can make a few enhancements.

Removing Unnecessary Parenthesis

The parenthesis around the parameters are required if there are no parameters or more than one parameter. However, when your arrow function only has one parameter, you can leave out the parenthesis to simplify it a bit like so.

const multiplyByTwo = num => {
    return num * 2;
}

Implicit Return

Often times, we write functions that return after just one line of code. With the “old” way of writing functions, the number of lines in the function didn’t affect how you defined the function. With arrow functions, it can.

If the only thing you want to do in a function is a one-line return, you can use *_implicit return *_to greatly simplify your function. While using implicit return, you don’t need the curly braces or the return keyword. It would look like this.

const multiplyByTwo = num => num * 2;

One thing to think about it is that you can still use the implicit return syntax even if you don’t necessarily need to return anything. In other words, if the callers of your function are not expecting it to return anything, then having it return something doesn’t matter.

For example, if I just wanted to print something to the console, I could use implicit return to shorten the length of the function.

const printName = (first, last) => console.log(`${first} ${last}`);

Using Arrow Functions in Map and Filter

One of the most common places you’ll see arrow functions used are with JavaScript Array methods like map, reduce, filter, etc. By use arrow functions with these methods, you can make complete array transformations in just one line.

Let’s look at two examples, one with map and one with filter. For the map version, let’s say we want to convert an array by multiplying each number by two. It would look something like this.

const twodArray = [1,2,3,4].map( num => num * 2);


Notice with this arrow function, I left off the parenthesis (because there’s only one parameter) and used implicit return. This kept the entire transformation to one line!

Now, let’s do another with filter. Let’s say we want to filter all numbers that are not even.

const filteredArray = [1,2,3,4].filter( num => num % 2 == 0);


Again, no parenthesis and implicit return. Super quick to make array transformations with just one!

‘This’ Binding with Arrow Functions

The conversation around the _this _keyword is definitely intermediate JavaScript, so you might need to do a little bit of additional research for this section. Regardless, let’s start with an example using an ES5 function definition inside of a person object.

const person = {
    first: "James",
    last: "Quick",
    getName: function() {
        this.first + " " + this.last
    }
}

In this case, we created a person object with a first and last name as well as a getName() function that returns the full name of the person. Inside of the function, we are trying to reference the first and last properties, by calling this.first and this.last.

When ES5 functions are defined in an object, ‘this’ refers to the object itself.

The reason we are able to access those properties through the this keyword, is that when those functions are defined inside of an object, it is automatically bound to the object itself. Therefore, with ES5 functions, we can still reference the object propreties by using ‘this’.

Arrow functions don’t bind anything to the keyword ‘this’.

However, when you use arrow functions, things change a bit. Arrow functions don’t do any binding for the keyword this. Therefore, if we were to change the function definition to be an arrow functions, things wouldn’t work.

const person = {
    first: "James",
    last: "Quick",
    getName: () => {
        return this.first + " " + this.last
    }
}

In this case, undefined would be printed for both the first and last property. The reason is since the keyword ‘this’ is not bound to the person object, it doesn’t have a first and last variable to refer to.

Understanding the difference between using this in arrow functions is really important!

Wrap Up

Arrow functions are one of many nifty little features of ES6 JavaScript. You will see them used more and more in examples and documentation, so it’s worth learning how they work. Not to mention, they can significantly improve the conciseness and readability of your code!

#javascript #es6 #web-development

What is GEEK

Buddha Community

Getting Started with ES6 Arrow Functions in JavaScript
Vincent Lab

Vincent Lab

1605017502

The Difference Between Regular Functions and Arrow Functions in JavaScript

Other then the syntactical differences. The main difference is the way the this keyword behaves? In an arrow function, the this keyword remains the same throughout the life-cycle of the function and is always bound to the value of this in the closest non-arrow parent function. Arrow functions can never be constructor functions so they can never be invoked with the new keyword. And they can never have duplicate named parameters like a regular function not using strict mode.

Here are a few code examples to show you some of the differences
this.name = "Bob";

const person = {
name: “Jon”,

<span style="color: #008000">// Regular function</span>
func1: <span style="color: #0000ff">function</span> () {
    console.log(<span style="color: #0000ff">this</span>);
},

<span style="color: #008000">// Arrow function</span>
func2: () =&gt; {
    console.log(<span style="color: #0000ff">this</span>);
}

}

person.func1(); // Call the Regular function
// Output: {name:“Jon”, func1:[Function: func1], func2:[Function: func2]}

person.func2(); // Call the Arrow function
// Output: {name:“Bob”}

The new keyword with an arrow function
const person = (name) => console.log("Your name is " + name);
const bob = new person("Bob");
// Uncaught TypeError: person is not a constructor

If you want to see a visual presentation on the differences, then you can see the video below:

#arrow functions #javascript #regular functions #arrow functions vs normal functions #difference between functions and arrow functions

JavaScript: The Good Parts of Arrow Functions

When I was at a coding boot camp learning about JavaScript and ES6, everyone in class seemed to have some level of confusion around normal function declarations and the new ES6 arrow function declarations. Common questions we had included:

  • When should we use normal functions or arrow functions?
  • What are the differences between normal functions and arrow functions?
  • Are we able to use one or the other in all situations for consistency?

After doing some research, I found that normal functions and arrow functions are actually not interchangeable in certain circumstances. Apart from the syntax, normal functions and arrow functions have another major difference: the way they bind the this keyword in JavaScript.

Let’s look at a very simple example. Suppose we have a simple JavaScript object:

const obj1 = {
	  fullName: 'Object 1',
	  color: 'red',
	  print: function() {
	    console.log(`${this.fullName} is ${this.color}`);
	  }
	};

	obj1.print(); // Object 1 is red
view raw
object1.js hosted with ❤ by GitHub

We have a print method on obj1 that logs a string to the console. The result is what we have expected, that this in the print method refers to obj1 itself.

Now let’s create another object with a slightly different print method:

const obj2 = {
	  fullName: 'Object 2',
	  color: 'blue',
	  print: function() {
	    setTimeout(function() {
	      console.log(`${this.fullName} is ${this.color}`);
	    }, 1000);
	  }
	};

	obj2.print(); // undefined is undefined
view raw
object2.js hosted with ❤ by GitHub

Now the print method will only log the resulting string after one second due to setTimeout . But why is it logging undefined is undefined instead of Object 2 is blue ?

#es2015 #javascript #es6 #javascript-tips #arrow-functions #function

Kaustav Hazra

1603269637

Dissecting a Compound Arrow Function in JavaScript

Arrow functions, introduced in ES6, can be quite concise compared to traditional functions. If you don’t like the extra syntax of a traditional function, the streamlined nature of an arrow function can be very appealing. Furthermore, if you need to perform something a little more complex, stringing together a couple of these allows you to achieve the desired results without having your codes looking too convoluted. Let me illustrate with an example.

Let’s say I have an array containing data from one table and I want to augment each table row with additional data elements from another table, assuming there are foreign keys that tie the two tables. The example code is written with React/Redux but I will bypass the part of populating the Redux store with JSON data from backend API. Just remember that the two Redux store items in question contain the two tables we are working with.

#arrow-functions #es6 #javascript #map-function

Condo Mark

Condo Mark

1594610031

JavaScript = Arrow Functions => ES6

Arrow function (also known as “fat arrow; =>” function) was introduced in ECMAScript 2015 as a new syntax for declaring functions.

Two main differences between an arrow function and a regular function are:

1.Basic Syntaxes:

Arrow functions provide a more concise syntax for writing function expressions. They allow us to have implicit returns with a shorter syntax by removing curly brackets {} and return keyword. The details will be explained in this article with examples.

2. The Way **this** Binds:

Arrow functions do not have their own bindings to this, unlike regular functions. They have lexically bound this meaning that the value of their this is determined by the scope that they are in. The behavior of this keyword is not the focus of today’s article, it will be explained in another post.

Basic Syntax of Array Functions

Arrow functions introduce a shorter function syntax than regular functions, let’s take a look at the following code examples to understand the difference.

Here is how we declare a function:

Image for post

The same function can also be written like the following by storing it in a variable to call later with that name:

Image for post

We will need to declare arrow functions as variables because they are anonymous functions means that they are not named.

Now, let’s convert the above function into an arrow function:

Image for post

As you see in the example, the function keyword is dropped and fat arrow(=>) comes after the parameter ; (color), and before the curly brackets {}.

#web-development #javascript #arrow-functions #es6 #programming

Giles  Goodwin

Giles Goodwin

1603176407

The real reason why JavaScript has arrow functions

Nowadays, all my code is based on the use of arrow functions. If you are still not using them yourself, then don’t be ashamed of who you are. That’s your parent’s job. Instead, find about all the benefits that you can get by using arrow functions like the cool kids.

This is an example of arrow function and the same code written traditionally:

const arrowFunction = (arg1, arg2) => arg1 + arg 2;

const traditionalFunction = function(arg1, arg2) {
  return arg1 + arg2;
};

You may notice that the code is shorter and that there is an arrow. Everything before the arrow is arguments of the function and everything after the arrow is always returned as the result of the function.

If you need a function that contains multiple statements you can still do this:

const arrowFunction = (arg1, arg2) => {
  const result = arg1 + arg2;
  return result;
};

#javascript #js #functional-javascript #functional-programming #javascript-tips