Thanks to ES6, we have a more concise way of writing functions, called Arrow Functions. Do you know the differences between a regular function and an arrow function ? Let me explain …
// Function expression
const greet = function (name) {
return `Hello ${name}`;
}
// Arrow Function with one parameter
const greet = name => {
return `Hello ${name}!`;
}
// Arrow function with two parameters
const greet = (name, age) => {
return `Hello, my name is ${name} and I am ${age} !`;
}
Arguments
Inside a regular function, you can access the list of the arguments that the function received when invoked with a special keyword arguments
:
function myFunction() {
console.log(arguments);
}
myFunction('a', 'b'); // logs { 0: 'a', 1: 'b', length: 2 }
Inside arrow functions, the arguments
special keyword doesn’t exist. It will throw an error of arguments is not defined
Implicit return
With arrow function, you don’t necessarily need to put a return statement at the end.
If your function only contains one expression you don’t need to write the curly braces or the return statement, the function will implicitly return the result of the expression :
const increment = num => num + 1;
increment(41); // returns 42
With a regular expression, if the return
statement is missing, the function will return undefined
:
function myFunction() {
'Hello';
}
myFunction(); // returns undefined
This
Arrow functions do not have their own this
. If you don’t know what the keyword this is, let me explain.
Inside a function, this
is an object, referring to the execution context. The value of the object is dynamic, depending on how you invoke the function expression.
Inside an arrow function this
always equals the value of the outer environment, it doesn’t define its own execution context.
New
With the keyword new
you can create instances of an object type. For instance, if we create a Plane object, we can invoke a new instance of Plane called “redPlane” of type Plane
function Dog(breed) {
this.breed = breed;
}
const shibaInu = new Dog('Shiba inu')
But arrow functions can’t be used as constructors, so you can’t invoke them with new
. If you try, you will receive the follow error : TypeError: Car is not a constructor
function Dog(color) {
this.breed = breed;
}
const shibaInu = new Dog('Shiba inu'); // TypeError: Dog is not a constructor
Duplicate named parameters
Inside a regular function, you use multiple times the same name for parameters (if you are not in strict mode) :
function add(x, x){ return x + x }
With arrow functions, it is completely forbidden and it an error will be thrown :
SyntaxError: duplicate argument names not allowed in this context
When would you choose to use one over the other? I think it's just a matter of preference, but let me know if you think I'm wrong!
I am really interested to know which syntax you use to define your functions. Do you prefer arrow functions or regular functions ?
Thank you and happy coding 👋
Photo by Juanjo Jaramillo on Unsplash
Top comments (0)