Javascript ES6 — Arrow Functions # 3

Arrow functions is a new way of writing functions using a simpler syntax, and the version of javascript that supports arrow functions is es6, or ECMAScript 6, in general, many modern browsers supporting the use of arrow functions, however, if you’re in a situation of cross-browser validation, when you’ve to support old javascript versions like es5, in this case you can transpile your code to an older version.

Okay, let’s move to our subject, sometimes arrow functions can also be called fat arrow functions, because of the used fat arrow symbols, and let’s just list some of the pros of this new syntax.

Pros

Arrow functions can also be considered as anonymous functions, they change the
way the keyword this bind in function, they make code concise, and you can also
eliminate the basic keywords like function, return and even the brackets

Cons

Some of the cons of this new way of writing functions are confusing rules and
syntax, and it can sometimes make code difficult to read. Basic Syntax with
multiple parameters lets head to a simple example of a basic function syntax
with multiple parameters, first, create a variable sayHello that have as a value
an anonymous function and that have two parameters a firstName and a lastName,
and it’ll will return a greeting hello message.

const sayHello = function(firstName, lastName) {
 return "Hello," + firstName + " " + lastName;
};

lets console.log the result, and use for the firstName Joe and for the lastName
Doe. console.log(sayHello(“John”, “Doe”) The returned value is Hello, John Doe.
Okay, this is the simple presentation, now let’s convert this simple function to
an es6 arrow function presentation, first, you’ve to remove the function
keyword, and you add a fat arrow after the arguments.

let sayHello = (firstName, lastName) => {
   return "Hello," + firstName + " " + lastName;
}

Our function doesn’t include too much logic, you’ve only a returned value, so,
you can even simplify it by removing the brackets and the return keyword.

const sayHello = (firstName, lastName) => "Hello," + firstName + " " + lastName;

Basic syntax with one parameter let’s go to another example that uses one
argument, so we’ll start with the traditional presentation, create a new
variable getName equal to an anonymous function that has a one parameter name
and returns a hey plus a given name.

const getName = function(name) {
 return "Hey," + "" + name;
};

console log the result

console.log(getName("John Doe"))

now, and like the previous example, to change this presentation to an es6
syntax, remove the function keyword, add a fat arrow after the function
parameter, remove the brackets and remove the return keyword

const getName = (name) => "Hey," + "" + name;

In this example, the function has only one parameter so you can simplify it by
removing the parentheses around the parameter.

const getName = name => "Hey," + "" + name

No parameters in case your function has no parameter, let’s create a function
sayHey with no parameters, that return a hey message.

const sayHey = function () {
     return "Hey!"
}

okay again, you remove the function keyword, however, you keep the parenthesis,
add the fat arrow remove the brackets and remove the return keyword. Object
literal Syntax like a regular function expression, arrow functions can also
return a literal object syntax, the only difference that you’ve to use
parentheses instead of brackets to differentiate between a block and an object.

Let’s create a function getStudentInfos using the es6 syntax, for that, do a
variable getStudentInfos equals to an anonymous function, this function has no
parameter, so add parentheses, plus the fat arrow symbol, and now, and because
the returned value has to be an object, you open the parentheses, and you
include the object, the info that you want the function return, is the name that
has a value of John Doe, and age with the value 20.

const getStudentInfos = () => ({
      name: "John Doe",
      age: 20
});

let’s do a const student equal the returned value of getStudentInfos.

const student = getStudentInfos();

console log the result

console.log(student)

as you see we have an object as a returned value.

“this” keyword

As already mentioned on the intro, “this” behave differently in arrow functions,
and using them will help you lot avoiding the confusion surrounding the this.
Because sometimes, if you’re in a case of keeping track of the context of this
within nested functions, in the older way of es5, you’ll be obligated of using
var “self” equal to “this”

var self = this;

or workarounds using bind, so, let’s do a bind example using es5 version, you’ll
create a function that will keep track of a number within an object and
increment it by one after a defined time, one second. for that, create an object
incrementedNumber that has two properties, one is the number you want to
increment, the number is 42, and two, a function increment that will keep track
of the number value and increment it by one, so the property name is increment,
that has as a value a function increment, we want to increment the number after
one second, so, setTimeOut, the first parameter of settimeout is the returned
value, which is an anonymous function and you bind this to it, this function
will keep track of the number there and add one to it, so, console log “this”
dot number plus equal one, and as a second parameter for the settimeout is the
defined time in millisecond, which it’s 1000 milliseconds

var incrementedNumber = {
 number: 42,
 increment: function increment() {
   setTimeout(
     function() {
       console.log((this.number += 1));
     }.bind(this),
     1000,
   );
 },
};

Now from the object incrementedNumber let’s call the function increment.

incrementedNumber.increment();

As you see console log display 43 by getting the value of number mapped into
this keyword, if I remove the bind function, this will be unknown and I can’t
access to the value of the number within the object.

var incrementedNumber = {
 number: 42,
 increment: function increment() {
   setTimeout(
     function() {
       console.log((this.number += 1));
     },
     1000,
   );
 },
};

Lets return the bind keyword.

var incrementedNumber = {
 number: 42,
 increment: function increment() {
   setTimeout(
     function() {
       console.log((this.number += 1));
     }.bind(this),
     1000,
   );
 },
};

If you keep Duplicating the increment function calls, this will keep track of
the last incremented numbers and increment it by one.

incrementedNumber.increment();
incrementedNumber.increment();
incrementedNumber.increment();

So you’ll have as a result 43, 44 and 45. But the goal is not to use the bind
function, so using the arrow function will map this keyword into your function,
okay, let’s rewrite the function increment within the object to an arrow
function. Instead of using a property name plus a value, use the function name
directly plus the parentheses, remove the function keyword from the first
parameter of the setTimeout, remove the bind function, you don’t need it
anymore,

const incrementedNumber = {
 number: 42,
 increment() {
   setTimeout(() => {
     console.log((this.number += 1));
   }, 1000);
 },
};

Conclusion

that’s it, you’ve got the same result, and you’re keeping track of the “this”
keyword without using bind.

Leave a Reply

Your email address will not be published. Required fields are marked *