Normal Function vs Arrow Function
Normal Function:
function App() {
return {
// Function body goes here
};
} // The function name `App` holds a reference to the function
Arrow Function:
const App = () => {
<View></View>
} // The variable name `App` holds a reference to the arrow function
Comparing Normal with Arrow Function:
The
function App()
is replaced withconst App = () =>
, whereconst
is used to make sure that no other Variable is assigned with the nameApp
, In case offunction App()
, the function is bound with the name of the functionApp
The
const
keyword in an arrow function is used to declare a constant variable that holds the function itself. In the case of an arrow function assigned to a variable, usingconst
ensures that the variable cannot be reassigned to a different value or reference another function.On the other hand, the regular function declaration syntax does not require the use of
const
or any other specific keyword. When using the regular function syntax, the function name itself is used as a variable to hold the function reference.
Advantages of using Arrow Function.
Concise Syntax:
Regular function
function multiply(a, b) { return a * b; }
Arrow Function
function multiply(a, b) { return a * b; }
In this example, the arrow function syntax allows us to define the function in a more compact manner. The return
statement is implicit, and the function body is reduced to a single line.
Implicit '
this
' binding:Regular function:
const obj = { name: 'John', greet: function() { console.log('Hello, ' + this.name); } };
Arrow function:
const obj = { name: 'John', greet: () => { console.log('Hello, ' + this.name); } };
In the regular function,
this
refers to the object (obj
) on which the method is invoked. However, in the arrow function,this
refers to the surrounding scope, which is the global scope in this case. As a result, the arrow function will not correctly access thename
property of the object.