DEV Community

Cover image for Arrow functions in React
Anil
Anil

Posted on

Arrow functions in React

Arrow functions are a concise way to write anonymous function expressions in JavaScript. They were introduced in ES6 (ECMAScript 2015) and provide a more compact syntax compared to traditional function declarations. Here are some examples demonstrating the usage of arrow-functions:

  1. Basic arrow function syntax:
const greet = () => {
  console.log("Hello!");
};
greet(); // Output: Hello!

Enter fullscreen mode Exit fullscreen mode
  1. Arrow function with parameters:
const greetWithName = (name) => {
  console.log(`Hello, ${name}!`);
};
greetWithName("Alice"); // Output: Hello, Alice!

Enter fullscreen mode Exit fullscreen mode
  1. Arrow function with implicit return:
const square = (x) => x * x;
console.log(square(5)); // Output: 25

Enter fullscreen mode Exit fullscreen mode
  1. Arrow function with multiple statements:
const sum = (a, b) => {
  const result = a + b;
  return result;
};
console.log(sum(3, 4)); // Output: 7

Enter fullscreen mode Exit fullscreen mode
  1. Arrow function as a callback:
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]


Enter fullscreen mode Exit fullscreen mode
  1. Arrow function with destructuring:
const person = { name: "John", age: 30 };
const greetPerson = ({ name, age }) => {
  console.log(`Hello, ${name}! You are ${age} years old.`);
};
greetPerson(person); // Output: Hello, John! You are 30 years old.

Enter fullscreen mode Exit fullscreen mode
  1. Arrow function in higher-order functions:
const multiplier = (factor) => (value) => value * factor;
const double = multiplier(2);
console.log(double(5)); // Output: 10
const triple = multiplier(3);
console.log(triple(5)); // Output: 15


Enter fullscreen mode Exit fullscreen mode

Arrow functions have lexical scoping of the this keyword, meaning they do not have their own this context. Instead, they inherit this from the surrounding code. This behavior can sometimes lead to unexpected results when using arrow functions as methods on objects or when using them with this.

github
website

Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js

Top comments (0)