ES6 Arrow Functions

hellomeghna

Meggie

Posted on February 20, 2019

ES6 Arrow Functions

They are next-generation JavaScript syntax for creating functions.

Normal JavaScript function syntax:

function myFunc() {
    ...
}

ES6 fat arrow function syntax:

const myFunc = () => {
    ...
}

Why we prefer ES6 arrow functions?

They can shorten the JavaScript function syntax, since:

  • Omits function keyword
  • Solves a lot of issue with this keyword in JavaScript.
    • this keyword is important when we add method to an Object.
    • Arrow Functions bind their context and not change in runtime so this actually refers to the originating context.

Practice time!

function printMyName(name) {
    console.log(name);
}
printMyName('Meggie'); //Meggie

Rewritten as:

const printMyName = (name) => {
    console.log(name);
}
printMyName('Meggie'); //Meggie

We can also shorten the syntax more!

How?

  • If we’re passing only one argument, we can omit the parenthesis too to shorten the syntax.
const printMyName = name => {
  console.log(name);
}
printMyName('Meggie');

Similarly, see another function -

const multiplyNum = num => {
    return num*2
}
console.log(multiplyNum(5)); //10
  • If there’s only one line of code returning something, we can omit the curly braces {} and return keyword too, and bring the whole code in one line!
const multiplyNum = num => num*2;
console.log(multiplyNum(5)); //10

Conclusion

ES6 arrow functions are a new cool way to write JavaScript functions in less lines of code.
Happy Comic Face

💖 💪 🙅 🚩
hellomeghna
Meggie

Posted on February 20, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ES6 Arrow Functions
es6 ES6 Arrow Functions

February 20, 2019