Function is an essential building block in JavaScript. The purpose of using function is the same as defining procedure - a set of statements that performs a task or calculates a value. Moreover, a procedure is qualified as a function if it takes some input and returns a corresponding output.
In order to declare a function,function
expression should be followed by:
- the name of the function,
- a list of parameters to the function (enclosed in parantheses and separated by commas),
- the JavaScript statements that define the function, enclosed in curly brackets,
{...}
Below is the example of function named add
function add (num1, num2) {
return num1 + num2;
}
In 2015, ES6 comes to bring new handy approach, so called arrow function which a compact alternative compared to traditional function
expression. Above add
function could be converted as below
const add = (num1, num2) ⇒ {
return num1 + num2;
}
// you can remove parentheses and return keyword
// more concise function will be like below
const add = (num1, num2) ⇒ num1 + num2;
However, arrow function has also several limitation and can’t be used in all situations:
- Does not have its own bindings to
this
orsuper
, and should not be used asmethods
. - Does not have
new.target
keyword. - Not suitable for
call
,apply
, andbind
methods, which generally rely on establishing ascope
. - Can not be used as
constructors
. - Can not use
yield
, within its body.
According to the first limitation, arrow function is not suited for non-methods functions. JavaScript can define a method inside an object.
Below is the example of staff
object with sayName
method.
let staff = {
name: 'Staff One',
sayName: function() {
console.log(`My name is ${this.name}`)
}
}
staff.sayName() // prints 'My name is Staff One' in your console
It’s intriguing to use the arrow function and replace the function()
with () =>
.
let staff = {
name: 'Staff One',
sayName: () => {
console.log(`My name is ${this.name}`)
}
}
staff.sayName() // prints 'My name is undefined' in your console
However, arrow function doesn’t have bindings to this
, and it makes staff.sayName()
will print My name is undefined because the this.name
can’t be referred to staff.name
.
Furthermore, in order to define a method inside JavaScript object, is to use traditional function
expression that can be defined as:
let staff = {
name: 'Staff One',
sayName: function() {
console.log(`My name is ${this.name}`)
}
}
staff.sayName() // prints 'My name is Staff One' in your console
or
let staff = {
name: 'Staff One',
sayName() {
console.log(`My name is ${this.name}`)
}
}
staff.sayName() // prints 'My name is Staff One' in your console
Both of them, is eligible to be called by staff.sayName()
and it will produce the right output.
Conclusion
To sum up, the arrow function deliver more concise and handy alternative to declare a function. However, we also need to be aware with the limitation it brings and use it in the right way.
Comments (0)