0
0
Javascriptprogramming~5 mins

Arrow functions in Javascript

Choose your learning style9 modes available
Introduction

Arrow functions let you write small functions quickly and clearly. They make your code shorter and easier to read.

When you want a quick function without writing the full function keyword.
When you need to keep the meaning of 'this' inside a function.
When writing simple one-line functions like math calculations or returning a value.
When using functions inside array methods like map, filter, or forEach.
Syntax
Javascript
const functionName = (parameters) => {
  // code here
};

If there is only one parameter, you can skip the parentheses.

If the function body is a single expression, you can skip the curly braces and the return keyword.

Examples
A simple arrow function with no parameters that prints a greeting.
Javascript
const greet = () => {
  console.log('Hello!');
};
One parameter without parentheses and a single expression returning the square of x.
Javascript
const square = x => x * x;
Multiple parameters with curly braces and explicit return.
Javascript
const add = (a, b) => {
  return a + b;
};
Sample Program

This program uses an arrow function inside the map method to double each number in the array.

Javascript
const numbers = [1, 2, 3, 4];

// Use arrow function to double each number
const doubled = numbers.map(n => n * 2);

console.log(doubled);
OutputSuccess
Important Notes

Arrow functions do not have their own 'this' keyword; they use 'this' from the surrounding code.

They cannot be used as constructors (you cannot use 'new' with arrow functions).

Summary

Arrow functions provide a shorter way to write functions.

They are great for small, simple functions and callbacks.

Remember their special behavior with 'this' compared to regular functions.