Dylan  Iqbal

Dylan Iqbal

1559956225

ES6 Arrow Functions Cheatsheet

Here’s a cheatsheet to show you the many ways to write your arrow functions.

// Explicit Return, Multi-Line
a => {
  return a
}

// Explicit Return, Single-Line
a => { return a }

// Implicit Return, Multi-line
a => (
  a
)

// Implicit Return, Single-Line
a => a

// Multiple Parameters, Parentheses Required
(a, b) => a, b


Implicit vs Explicit Return

We have several ways of writing our arrow functions. This is because arrow functions can have either “implied return” or “explicit return” keyword.

With normal functions, if you want to return something, you have to use the return keyword. Arrow functions also have that. When you use the return keyword, it’s called an explicit return. However, arrow functions up their game and allow something called implied return where the return keyword can be skipped. Let’s look at some examples 🤓:

Example A: Normal Function

const sayHi = function(name) {
  return name
}


Example B: Arrow Function with Explicit Return

// Multi-line
const sayHi = (name) => {
  return name
}

// Single-line
const sayHi = (name) => { return name }


Example C: Arrow Function with Implicit Return

// Single-line
const sayHi = (name) => name

// Multi-line
const sayHi = (name) => (
  name
)


Notice the difference? When you use curly braces {}, you need to explicitly state the return. However, when you don’t use curly braces, the return is implied and you don’t need it.

There’s actually a name for this. When you use curly braces like in Example b, it’s called a block body. And the syntax in Example c is called a concise body.

⭐️ Here are the rules:

  • Block body ➡️ return keyword is required
  • Concise body ➡️ return keyword is implied and not needed

Parentheses

With a normal function, we always had to use parentheses. However, with Arrow Functions, parentheses are optional if there is ONLY one parameter.

Parentheses are optional for a SINGLE parameter

// Normal Function
const numbers = function(one) {}

// Arrow Function, with parentheses
const numbers = (one) => {}

// Arrow Function, without parentheses
const numbers = one => {}


Parentheses are required for MULTIPLE parameters

// Normal Function
const numbers = function(one, two) {}

// Arrow Function, with parentheses
const numbers = (one, two) => {}


⚠️ Arrow Functions Gotcha: Returning Objects

Remember I mentioned about the different body types - concise body and block body. Just to quickly update you in case you skipped that section (I’m bit sad you, but not offended 😝). Block body is where you use curly braces and have an explicit return. Concise body is where you don’t use curly braces, and you skip the return keyword. Alright, now you’re caught up, let’s get back to the gotcha 🤯

Let’s purposely break our code, so you can learn your lesson lol 😂

const me = () => { name: "samantha" };

me(); // undefined 😱


What?! Why isn’t it returning my object. Don’t worry, let’s fix it by wrapping it in parentheses.

const me = () => ({ name: "samantha" });

me(); // { name: "samantha" } ✅


⭐️ Here’s the rule:

  • Block body ➡️ return keyword is required
  • Concise body ➡️ return keyword is implied and not needed

Resources

  • Block body ➡️ return keyword is required
  • Concise body ➡️ return keyword is implied and not needed

#javascript

What is GEEK

Buddha Community

ES6 Arrow Functions Cheatsheet
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

Duy  Tien

Duy Tien

1626366000

Sử dụng Arrow function trong ES6 #10

Sử dụng Arrow function trong ES6

#es6 #arrow function