Functions and Arrow Functions


Overview

Functions and arrow functions serve the same purpose. In this article we will see what functions and arrow functions are and their major differences.

functions

When we often want to perform the same task in multiple places on a website or application, we use the concept called function.

A function is a block of code that performs a specific task.

A function is declared by the keyword function and followed by the name of the function.

Syntax:

Inside parentheses we can declare a list of parameters.

Example:

In the above example greetMessage is the name of the function and name, greet are the parameters of the function, and the text inside the curly braces is the function body.

42Gears,Hello are the function arguments in first greetMessage.

When a value is passed as a function parameter, it’s also called an argument.

The difference between parameter and argument is that parameters are listed in the function declaration, i.e., inside the parentheses after the name of the function, whereas argument is the value passed to the function when it is called.

Example 3:

The return statement stops the execution of a function and returns a value.

Arrow Functions

The other way to create a function which is better than the regular function, i.e. Arrow function

Arrow function is also called a fat arrow.

The below examples are for arrow function and the same example we have taken for function as well.

Syntax:

Example1:

Example2:

Major differences between functions and arrow functions

functions arrow functions
Syntax

Syntax
Argument Binding is possible

Argument Binding is not possible
Regular functions allow us to use duplicate named parameters. But in strict mode, it is not allowed
Ex:
function name(Mobility, Mobility){}
In arrow functions, parameters with the same name are not allowed whether the strict mode is enabled or not.
Ex:
let name = (Mobility, Mobility) => {} //Uncaught SyntaxError: duplicate argument names not allowed in this context
Usage of this keyword
Its value is dynamic and depends on the invocation.
Usage of this keyword
It is lexically bounded and equal to the outer function.
Use of new keyword
If we want to create a new object we can use new keyword
Example:
Use of new keyword
We can not call new keyword in arrow functions
Example:

Conclusion

Functions and arrow functions serve the same purpose, but arrow functions have less syntax and require less code and readable code.

Leave A Comment

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