Arrow Functions
Arrow Functions are a shorter and cleaner way to write functions in JavaScript. They use the => arrow syntax instead of the traditional function keyword.
Arrow Functions use the => syntax to write functions in a shorter form.
Simple Explanation
Think of an Arrow Function as a shorter way to write
a normal JavaScript function.
A normal function uses the
function
keyword. An Arrow Function removes the
function
keyword and uses the
=>
symbol.
Arrow Functions make many common functions shorter
and easier to read.
Basic Syntax
The basic structure of an Arrow Function contains parameters, the arrow symbol, and the function body.
Parts of an Arrow Function
The function is commonly stored inside a variable using const.
Parameters receive values passed to the function.
The => symbol is the main syntax of an Arrow Function.
The function body contains the code that executes when the function is called.
Arrow Function Flow
(a, b)
Arrow
a + b
30
Example 1: Basic Arrow Function
A simple Arrow Function can execute a statement when it is called.
const greet = () => {
console.log("Hello JavaScript");
};
greet();
Hello JavaScript
Example 2: Arrow Function with Parameters
An Arrow Function can receive values through parameters.
const greetUser = (name) => {
console.log("Hello " + name);
};
greetUser("Rahul");
Hello Rahul
Example 3: Arrow Function with Return Value
An Arrow Function can return the result of a calculation.
const add = (a, b) => {
return a + b;
};
const result = add(10, 20);
console.log(result);
30
Example 4: Short Arrow Function
When an Arrow Function contains one expression, it can be written without curly braces and the return keyword.
const square = number => number * number;
console.log(square(5));
25
Normal Function vs Arrow Function
A normal JavaScript function uses the
function
keyword.
An Arrow Function uses the
=>
symbol instead.
The main advantage for beginners is that Arrow
Functions provide a shorter syntax for many
function expressions.
Arrow Functions do not use the function keyword. They use the => symbol.
Summary
An Arrow Function is a shorter way to write a JavaScript function using the => syntax. It can accept parameters, execute code, and return values. When a function contains a single expression, the syntax can be shortened further by using an implicit return.